ruby-on-rails – 将命名路由传递给RSpec中的控制器宏

我试图通过为常用测试添加一些控制器宏来干掉我的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 }

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...