Rick Peyton
Rick Peyton

Reputation: 69

How do I stub a method response inside a larger method?

I do not yet have a good grasp on mocking and stubbing. How would I go about stubbing the aodc.success? call to return false? The AodcWrapper::Order.create is not complete and will always return success today. But I need to simulate the fail case.

Here is the create method

def create
  @user = current_user
  @order = Order.new(order_params)
  if @order.valid?
    aodc = AodcWrapper::Order.create(@order)
    if aodc.success?
      # pending... Capture the authorization
      @order.save
      UserMailer.order_received_email(@user).deliver_later
      StaffMailer.order_received_email(@user).deliver_later
      render json: @order, serializer: Api::V1::OrderSerializer
    else
      render json: { status: :failure, error: aodc.error_message }
    end
  else
    render json: { status: :failure, error: @order.errors.full_messages }
  end
end

And here is the test

context "sad path 1: can not connect to the aodc" do
  before do
    @user = FactoryGirl.create(:user)
    @order = FactoryGirl.attributes_for(:shippable_order, user: @user)
    sign_in @user
    post :create, user_id: @user.id, order: @order
  end
  it "reponds with a could not connect message" do
    parsed_response = JSON.parse(response.body)
    expect(parsed_response[:error]).not_to be_nil
  end
end

Side quest. Any recommendations on resources to explore so that I can not suck at mocks and stubs?

Upvotes: 1

Views: 146

Answers (1)

Rick Peyton
Rick Peyton

Reputation: 69

So I was going about that completely wrong. The AodcWrapper was making an API call with Httparty.

The path I took to solve this was

  • Use VCR to record the API interaction
  • The test failed because the response was successful
  • Modify the VCR cassette yml and change the success response to my desired (not yet implemented) error message
  • Rerun the test and all is well.

Upvotes: 1

Related Questions