【问题标题】:RSpec & Rails: Stub request.path for helper specRSpec & Rails:帮助规范的存根 request.path
【发布时间】:2015-04-01 20:56:40
【问题描述】:

我在ApplicationHelper有这个方法:

def home_link_class
  classes = ['navbar-brand']
  classes << 'active' if request.path == root_path
  classes
end

我想这样测试它:

describe '#home_link_class' do
  before  { allow(helper.request).to receive(:path).and_return '/some-path' }
  subject { home_link_class }

  it { should eq ['navbar-brand'] }
end

遗憾的是,存根似乎不起作用,帮助程序本身中的 request 对象设置为 nil,即使在规范中它似乎是一个 ActionController::TestRequest 对象。

如何确保 request 在规范中可用?

【问题讨论】:

    标签: ruby-on-rails rspec request


    【解决方案1】:

    您需要存根请求本身以及路径的返回值。为存根 path 的请求定义一个测试替身:

    describe '#home_link_class' do
      let(:request) { double('request', path: '/some-path') }
    
      before  { allow(helper).to receive(:request).and_return(request) }
      subject { home_link_class }
    
      it { should eq ['navbar-brand'] }
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      相关资源
      最近更新 更多