在 Michael Hartl 的Ruby on Rails 教程,第 2 版,第 9 章的练习 6 中,说:
登录用户没有理由访问用户控制器中的新操作和创建操作。如果他们确实尝试访问这些页面,请安排将此类用户重定向到根 URL。
如何为此编写 rspec 测试?我试过这个
describe "POST on Users#create" do
before { post users_path }
specify { response.should redirect_to(root_path) }
end
我尝试过使用 do/end 块,添加用户属性的哈希等。上面的代码片段已添加到官方示例代码的第 162 行。他们都给我这个错误:
Failures:
1) Authentication authorization as non-admin user POST on Users#create
Failure/Error: before { post users_path }
AbstractController::DoubleRenderError:
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
# ./app/controllers/users_controller.rb:27:in `create'
# ./spec/requests/authentication_pages_spec.rb:72:in `block (5 levels) in <top (required)>'
Finished in 2.72 seconds
88 examples, 1 failure
至于限制对用户控制器中新操作和创建操作的访问的实际目标,我通过添加以下行来解决它们:
admin_user if signed_in?
我知道这很有效,因为我手动测试了它。唯一的问题是我无法为其编写 rspec 测试。我按照本教程创建的代码可在 github 上找到。
为什么我会收到此错误?我究竟做错了什么?解决办法是什么?谢谢你。