【问题标题】:Testing if a method from another scope has been called in a controller测试是否在控制器中调用了来自另一个范围的方法
【发布时间】:2020-01-28 16:14:55
【问题描述】:

我有以下控制器方法:

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

【问题讨论】:

    标签: rspec rspec-rails


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 2015-09-17
      • 2023-03-12
      • 2014-01-03
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多