【发布时间】:2012-04-17 09:55:59
【问题描述】:
我在 products_controller_spec.rb 中编写了这个规范,目的是在对不存在的记录调用 destroy 时测试重定向:
it "deleting a non-existent product should redirect to the user's profile page with a flash error" do
delete :destroy, {:id => 9999}
response.should redirect_to "/profile"
flash[:error].should == I18n.t(:slideshow_was_not_deleted)
end
这是 products_controller.rb 中的控制器操作:
def destroy
product = Product.find_by_id(params[:id])
redirect_to "profile" if !product
if product.destroy
flash[:notice] = t(:slideshow_was_deleted)
if current_user.admin? and product.user != current_user
redirect_to :products, :notice => t(:slideshow_was_deleted)
else
redirect_to "/profile"
end
else
if current_user.admin?
redirect_to :products, :error => t(:slideshow_was_not_deleted)
else
redirect_to "/profile"
end
end
end
现在,我没想到规范会第一次通过,但我不明白为什么它会失败:
Failure/Error: delete :destroy, {:id => 9999}
ActiveRecord::RecordNotFound:
Couldn't find Product with id=9999
我的印象是#find_by_id 不会在不存在的记录上返回 RecordNotFound 错误。那我为什么要买一个?提前致谢!
【问题讨论】:
-
您使用哪个版本的 Rails?这个
find_by_id在 Rails 3.2.3 中可以正常工作。 (返回 nil 而不是引发 RecordNotFound) -
3.2.2 在这里。我应该添加 find_by_id 在浏览器中工作。我只在规范结果中得到 RecordNotFound。
-
- 实际上,只是在浏览器中尝试对不存在的记录执行显示操作并得到 RecordNotFound。当我在控制器中注释掉 CanCan 身份验证时离开了。看起来 CanCan 正在扔 RnF
-
我目前没有足够的代表来回答这个问题,但简而言之,CanCan 在动作运行之前抛出了错误。它可以被修补,或者更简单地说,可以重写规范以期望 RnF。稍后我会将其作为正式答案发布。
标签: ruby-on-rails activerecord rspec cancan