4

我正在尝试通过为常用测试添加一些控制器宏来干燥我的 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)

我尝试根据此 SO 线程中给出的关于 RSpec 中命名路由的指南包含 Rails.application.routes.url_helpers ,但仍然收到相同的错误。

如何将命名路由作为参数传递给控制器​​宏?

4

1 回答 1

4

附带的 url 助手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 }
于 2013-01-13T17:56:04.620 回答