【发布时间】:2013-01-14 06:21:15
【问题描述】:
在 Michael Hartl 的 Ruby on Rails 教程,第二版,第 9 章的练习 6 中说:
已登录的用户没有理由访问新的和创建的操作 用户控制器。安排将此类用户重定向到 如果他们确实尝试访问这些页面,则为根 URL。
如何为此编写 rspec 测试?我试过这个
describe "POST on Users#create" do
before { post users_path }
specify { response.should redirect_to(root_path) }
end
我尝试过使用 do/end 块、添加用户属性的哈希等。上面的 sn-p 已添加到 the official sample code 中的 #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 测试。 The code I have created as I follow this tutorial is available at github.
为什么会出现此错误?我究竟做错了什么?解决办法是什么?谢谢。
【问题讨论】:
-
你的错误是
Render and/or redirect were called multiple times in this action。您能否编辑您的问题以在您的UsersController中添加create方法的内容。 -
您好 Paul,感谢您的回复。我已按要求编辑了我的帖子。但为了方便您,我的代码是in this link。其中,您应该能够看到我的用户控制器的全部荣耀。再次感谢您的帮助。
标签: ruby-on-rails-3.2 railstutorial.org ruby-1.9.3