NoMethodError: undefined method `stub!' for nil:NilClass

NoMethodError: undefined method `stub!' for nil:NilClass

我正在尝试将 rspec 用于 application_helper.rb 中存在的活动 link 条件。 Application_helper.rb代码:

def active_class(link_path)
    current_page?(link_path) ? 'active' : ''
  end

我试图将 rspec 用于此 active_class 方法,我为此使用了存根 purpose.This 是我的 rspec 代码用于 active_class 方法。 Application_helper_spec.rb代码:

describe 'when called from "index" action' do
  before
    helper.stub!(:action_name).and_return('index')
  end
  it 'should do' do
    helper.active_class.should == 'active'
  end


describe 'when called from "other" action' do
  before
    helper.stub!(:action_name).and_return('other')
  end
  it 'should do' do
    helper.active_class.should == 'empty'
  end

我收到未定义方法的错误stub.How我可以解决这个问题吗?

我使用略有不同的接口来进行存根和模拟,如下所示:

allow(helper).to receive(:action_name).and_return('index')

当您只想对响应进行存根时。

但是如果你需要设置一个期望:

expect(helper).to receive(:action_name).and_return('index')

您可以在文档中找到更多信息:https://relishapp.com/rspec/rspec-mocks/v/3-7/docs/basics