【问题标题】:RSpec stubbing issue -- stub seems to be working but not being receivedRSpec 存根问题 - 存根似乎正在工作但未收到
【发布时间】:2013-11-27 17:14:56
【问题描述】:

我是 RSpec 的新手,所以请耐心等待。我有一个带有订单的对象,我正在对该对象存根方法。我在该对象上调用另一个方法,然后调用我正在存根的方法(并且该存根似乎正在工作,因为我在所述方法调用周围放置了调试器并正确返回。另外,我在实际方法中投入了一个调试器调用;那没有被击中,所以它似乎是 stubing 好了)。

但是当我调用 @order.should_receive 时,我得到“预期 :blah_method with (any args) 一次,但收到了 0 次。”

我不确定为什么 should_receive 不起作用,也不确定我做错了什么。有什么帮助吗?顺便说一句,我正在使用 RSpec 1.3.2。

 it 'should be called when blah blah blah' do
  @order.stub!(:blah_method).and_return true
  #import_foobar_order calls @order.blah_method
  #order_hash is irrelevant here, just a json obj converted to a hash
  @order.import_foobar_order(@order, order_hash, website)
  @order.should_receive(:blah_method).at_least(:once)
end

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    should_receive 在调用之前进行,如果您使用 should_receive,则不需要存根(您可以在此处存根)

    it 'should be called when blah blah blah' do
      @order.should_receive(:blah_method).at_least(:once).and_return(true)
      @order.import_foobar_order(@order, order_hash, website)
    end
    

    【讨论】:

    • 你和我一样回答了,呵呵,但有趣的是我们的答案是一样的
    • 巴姆,谢谢!我想我必须先存根该方法,声明它应该接收什么,然后调用该方法。但你的方法行得通!
    【解决方案2】:

    should_receive 几乎充当存根。在执行方法之前设置它。因此,为了使测试正常工作,您应该这样做。

    it 'should be called when blah blah blah' do
      @order.should_receive(:blah_method).at_least(:once).and_return(true)
      @order.import_foobar_order(@order, order_hash, website)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多