Тестирование, если метод из другой области был вызван в контроллере - PullRequest
0 голосов
/ 28 января 2020

У меня есть следующий метод контроллера:

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

1 Ответ

1 голос
/ 28 января 2020

Вы можете установить ожидания для всех экземпляров класса, это не всегда идеально, но оно должно работать для вашего варианта использования:

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
...