完善控制器的 RSpec 宏
我正在尝试为使用 Devise 进行身份验证的 Rails 应用程序生成一个简单的宏。基本上我想确保当用户访问需要身份验证的页面时,他们会被重定向到登录页面。所以像这样:
it_requires_authentication_for :index, :new, :create, :update
这里想要的结果应该是显而易见的。然而,我的问题是,我想不出将每个操作映射到其适当的http方法(:get,:post等...)的最佳方法,
我从这个开始:
def it_should_require_authentication_for(*actions)
actions.each do |action|
it "should require authentication for #{action}" do
get action.to_sym
response.should redirect_to( new_user_session_path )
end
end
end
当然,它只执行get。有人可以告诉我如何为所有操作提供这个宏吗?我假设我需要以某种方式测试特定方法的操作是否正确路由,但我不太确定。
非常感谢任何帮助。
I'm trying to generate an easy macro for a Rails app that uses Devise for authentication. Basically I want to ensure that when a user accesses a page that requires authentication, they're redirected to the login page. So something like this:
it_requires_authentication_for :index, :new, :create, :update
The desired results here should be obvious. My problem however is that I can't think of the best way to map each action to its appropriate http method (:get, :post etc...)
I started out with this:
def it_should_require_authentication_for(*actions)
actions.each do |action|
it "should require authentication for #{action}" do
get action.to_sym
response.should redirect_to( new_user_session_path )
end
end
end
Which of course only does the get. Can someone tell me how I might provide this macro for all actions? I'm assuming I need to somehow test if the action routes properly for a particular method, but I'm just not really sure.
Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许老了,但仍然可以帮助一些人。
这是在 RSpec 中定义宏(甚至对于控制器)的一种很好且简单的方法。
http://osmose.6spot.com.br/2011/ 02/better-macros-with-rspec/
看,使用缺少的方法,您可以将特定行为记录到录制的宏中,例如,这是带有特定存根指令的脚手架控制器规范:
maybe old, but still can help some.
Here is a nice and easy way to define macros in RSpec (even for controllers).
http://osmose.6spot.com.br/2011/02/better-macros-with-rspec/
Look, using method missing you are able to record specific behavior into your recorded macros, for instance, this is a scaffold controller spec with a specific stub instruction:
我正在使用以下内容,直到我想出更优雅的东西:
顺便说一句,我仍然需要扩展它以使用以下路线:
I'm using the following until I come up with something more elegant:
BTW I still have to extend it to work with routes like:
此 Railscast 完全涵盖了您正在寻找的内容: http://railscasts.com/episodes/157 -rspec-matchers-macros
看起来您只需在控制器规范中使用所需的操作调用 get 方法,它将调用控制器中的适当方法。
这是我的宏版本:
This Railscast covers exactly what you are looking for: http://railscasts.com/episodes/157-rspec-matchers-macros
It looks like you can just call the get method with your desired action in your controller spec, and it will call the appropriate method in the controller.
Here is my version of the macro: