【问题标题】:Rspec test with mock for a static method and non static method使用模拟的 Rspec 测试静态方法和非静态方法
【发布时间】:2017-08-17 13:26:06
【问题描述】:

我有这样的方法:

def self.method
  #API CALL
end

我正在为调用此静态方法的控制器方法编写测试。是这样的:

it 'update order to confirmed' do
    Order.should_receive(:process_payment).and_return({})
    sign_in user
    attributes = FactoryGirl.attributes_for(:order, :valid_order)
    patch :confirm_order, params: { id: order.id, order: attributes }
    order.reload
    expect(order.confirmed).to eq true
end

而且运行良好。但是我不得不使这个方法不是静态的,并且测试开始失败。

在我的控制器中,我现在正在调用这样的方法:

Order.new.process_payment(@order)

我猜是我的模拟问题,但我不知道如何解决它。关于如何使我的模拟适应这种新格式的任何想法?

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec mocking


    【解决方案1】:

    你可以使用allow_any_instance_of方法:

    allow_any_instance_of(Order).to receive(:process_payment).and_return({})
    

    【讨论】:

      【解决方案2】:

      伊戈尔的回答很好。我也设法使它像这样工作:

      Order.any_instance.should_receive(:process_payment).and_return({})
      

      【讨论】:

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