测试控制器中是否调用了来自另一个作用域的方法

Testing if a method from another scope has been called in a controller

我有以下控制器方法:

def create_charge
    payment = Payment.where('order_id = ?', 1).first

    if payment.date <= Date.today
      err = payment.execute_off_session(customer.id, create_in_wms = true)
    else
      order.update_attributes(status: :partially_paid)
    end
end

我需要测试 execute_off_session 是否被调用。我找不到合适的方法来做到这一点:

describe Api::V1::OrdersController, type: :controller do
  describe "#create_charge" do
    context "fingerprinting a card only" do
      it "should'nt call #execute_off_session" do
        payment = instance_double("Payment")
        expect(payment).not_to receive(:execute_off_session)
        post :create_charge, {:params => {:uid => @order.uid}}
      end
    end
  end
end

您可以对 class 的所有实例设置期望值,这并不总是理想的,但它应该适用于您的用例:

describe "expect_any_instance_of" do
  before do
    expect_any_instance_of(Object).to receive(:foo).and_return(:return_value)
  end

  it "verifies that one instance of the class receives the message" do
    o = Object.new
    expect(o.foo).to eq(:return_value)
  end

  it "fails unless an instance receives that message" do
    o = Object.new
  end
end

(来源relishapp.com

你的情况:

describe Api::V1::OrdersController, type: :controller do
  describe "#create_charge" do
    context "fingerprinting a card only" do
      it "should'nt call #execute_off_session" do
        expect_any_instance_if(Payment).not_to receive(:execute_off_session)
        post :create_charge, {:params => {:uid => @order.uid}}
      end
    end
  end
end