在 RSpec 中将命名路由传递给控制器宏

4
我正在尝试通过添加一些控制器宏来使我的RSpec示例更加DRY。在这个有点简化的例子中,我创建了一个宏,仅测试获取页面是否导致直接转到另一个页面:
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,但仍然收到相同的错误。
如何将命名路由作为参数传递给控制器宏?
1个回答

4
< p >使用config.include Rails.application.routes.url_helpers包含的URL助手仅在示例(使用itspecify设置的块)内有效。在示例组(context或describe)中,您不能使用它。尝试使用符号和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 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接