【问题标题】:NoMethodError: undefined method `stub!' for nil:NilClassNoMethodError:未定义的方法“存根!”对于零:NilClass
【发布时间】:2018-05-22 11:24:22
【问题描述】:

我正在尝试将活动链接条件的 rspec 放在 application_helper.rb 中。 Application_helper.rb 代码:

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

我试图为这个 active_class 方法放置 rspec,为此我使用了 stub。这是我用于 active_class 方法的 rspec 代码。 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

我收到的错误是未定义的方法存根。我该如何克服这个问题?

【问题讨论】:

    标签: activerecord rspec specifications


    【解决方案1】:

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

    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

    【讨论】:

    • 感谢您的回复,当我在我的情况下添加此代码时,我收到错误为未定义的方法'to'。有没有更好的方法来改变这种情况?
    • 这很奇怪,因为它是标准 rspec 的一部分。您可以尝试使用 valilla rails + rspec 应用程序吗?也许您的一些 gem 或其他配置干扰了 rspec 模拟/存根库?
    猜你喜欢
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多