Baptiste Arnaud
Baptiste Arnaud

Reputation: 2760

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

I have the following controller method:

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

I need to test if execute_off_session has or hasn't been called. I can't find a proper way to do this:

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

Upvotes: 0

Views: 63

Answers (1)

Tibo
Tibo

Reputation: 61

You can set expectations on all instances of a class, it is not always ideal but it should work for your use case :

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

(source relishapp.com)

In your case :

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

Upvotes: 1

Related Questions