【问题标题】:Why is the stubbed method not called?为什么不调用存根方法?
【发布时间】:2012-05-06 23:06:32
【问题描述】:

我好像理解错了。我有课

module Spree
  class OmnikassaPaymentResponse
    #...
    # Finds a payment with provided parameters trough ActiveRecord.
    def payment(state = :processing)
      Spree::Payment.find(:first, :conditions => { :amount => @amount, :order_id => @order_id, :state => state } ) || raise(ActiveRecord::RecordNotFound)
    end
  end
end

在 Rspec 中指定:

describe "#payment" do
  it 'should try to find a Spree::Payment' do
    Spree::Payment.any_instance.stub(:find).and_return(Spree::Payment.new)
    Spree::Payment.any_instance.should_receive(:find)
    Spree::OmnikassaPaymentResponse.new(@seal, @data).payment
  end
end

然而,这总是抛出ActiveRecord::RecordNotFound。我希望 any_instance.stub(:find).and_return() 确保无论何时何地我在 Spree::Payment 的任何实例上调用 #find,它都会返回一些东西。

换句话说:我希望stub.and_return 会避免访问|| raise(ActiveRecord::RecordNotFound)。但事实并非如此。

我的假设错了吗,我的代码?还有什么?

【问题讨论】:

    标签: ruby testing rspec stub


    【解决方案1】:

    在您的情况下,find 不是实例方法,而是Spree::Payment 的类方法。这意味着您应该直接将其存根,而无需像这样 any_instance

    Spree::Payment.stub(:find).and_return(Spree::Payment.new)
    

    【讨论】:

    • 谢谢! FWIW:还必须在没有 any_instance 的情况下调用 .should_receive(:find)
    猜你喜欢
    • 2017-01-27
    • 1970-01-01
    • 2015-07-01
    • 2018-03-26
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多