【问题标题】:How to test content_for using rspec如何使用 rspec 测试 content_for
【发布时间】:2013-06-13 18:13:32
【问题描述】:

我正在尝试测试我的 application_helper 的 yield_for 方法,但我不知道最好的方法。我尝试了下面的代码,但收到以下错误:

 Failure/Error: self.stub(:content_for).with(:foo).and_return('bar')
   Stub :content_for received unexpected message :with with (:foo)

application_helper.rb

def yield_for(content_sym, default = '')
  content_for?(:content_sym) ? content_for(content_sym) : default
end

application_helper_spec.rb

describe '#yield_for' do
  it 'should fetch the yield' do
    self.stub(:content_for).with(:foo).and_return('bar')
    helper.yield_for(:foo).should == 'bar'
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec


    【解决方案1】:

    尝试在助手上制作存根

    it 'should fetch the yield' do
      helper.stub(:content_for).with(:foo).and_return('bar')
      helper.yield_for(:foo).should == 'bar'
    end
    

    用这个让你的测试通过了

    def yield_for(content_sym, default = '')
      content_for(content_sym) ? content_for(content_sym) : default
    end
    

    【讨论】:

    • 这给了我:Failure/Error: helper.yield_for(:foo).should == 'bar' expected: "bar" got: "" (using ==)
    【解决方案2】:

    我正在使用 rspec (3.1.0),它应该适用于:

    describe '#yield_for' do
      it 'should fetch the yield' do
        helper.content_for(:foo, 'bar')
        expect(helper.yield_for(:foo)).to eq('bar')
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 2018-07-30
      • 2018-08-23
      • 2013-12-07
      • 2019-12-10
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      相关资源
      最近更新 更多