我试图通过为常用测试添加一些控制器宏来干掉我的RSpec示例.在这个稍微简化的示例中,我创建了一个宏,它只是测试是否将页面结果直接转到另一个页面:
def it_should_redirect(method,path) it "#{method} should redirect to #{path}" do get method response.should redirect_to(path) end end
我试着像这样称呼它:
context "new user" do it_should_redirect 'cancel',account_path end
当我运行测试时,我得到一个错误,说它无法识别account_path:
undefined local variable or method `account_path’ for … (NameError)
我尝试按照this SO thread on named routes in RSpec中给出的指导包含Rails.application.routes.url_helpers,但仍然收到相同的错误.
如何将命名路由作为参数传递给控制器宏?
解决方法
config.include Rails.application.routes.url_helpers中包含的url帮助程序仅在示例中有效(使用它设置的块或指定的块).在示例组(上下文或描述)中,您无法使用它.尝试使用符号并发送,例如
# macro should be defined as class method,use def self.method instead of def method def self.it_should_redirect(method,path) it "#{method} should redirect to #{path}" do get method response.should redirect_to(send(path)) end end context "new user" do it_should_redirect 'cancel',:account_path end
不要忘记将url_helpers包含在配置中.
或者在示例中调用宏:
def should_redirect(method,path) get method response.should redirect_to(path) end it { should_redirect 'cancel',account_path }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。