我正在尝试通过为常用测试添加一些控制器宏来干掉我的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:
未定义的局部变量或方法`account_path'for ...(NameError)
我按照this SO thread on named routes in RSpec中给出的指导尝试包含Rails.application.routes.url_helpers但仍然收到相同的错误。
如何将命名路由作为参数传递给控制器宏?
答案 0 :(得分:3)
config.include Rails.application.routes.url_helpers
中包含的网址助手仅在示例中有效(使用it
或specify
设置的网址)。在示例组(上下文或描述)中,您无法使用它。尝试使用符号和send
,例如
# 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 }