加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:20:09 所属栏目:百科 来源:网络整理
导读:我试图通过为常用测试添加一些控制器宏来干掉我的RSpec示例.在这个稍微简化的示例中,我创建了一个宏,它只是测试是否将页面结果直接转到另一个页面: def it_should_redirect(method,path) it "#{method} should redirect to #{path}" do get method response
我试图通过为常用测试添加一些控制器宏来干掉我的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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读