Search code examples
ruby-on-rails-4webmock

Stubbing a 500 error


I am having an issue with webmocks stubbing.

This is a Rails 4 application using devise/cancan for Authentication and Authorisation. I am using RSpec to write my tests.

I have a (simplified for the cause of this post!) test that I'd like to run.

require 'rails_helper'

RSpec.describe ApiChecksController, type: :controller do

  include Devise::TestHelpers

  let(:user)          { FactoryGirl.create :user }
  let(:api_params) do
    {
      param_1: 'VALUE',
      param_2: '1980-01-01',
      param_3: 'AA123',
      param_4: "#{Date.today}"
    }
  end

  context 'logged in as standard user' do
  describe 'POST #lookup' do
      context 'displays error' do
        it 'when 500 returned' do
          WebMock.disable_net_connect!(allow: 'codeclimate.com')
          sign_in user
          stub_request(:post, "#{ENV['API_PROXY']}/api/checks").
            to_return(status: [500, "Internal Server Error"])
          post(:lookup, api_check: api_params)
          expect(response.status).to eq(500)
        end
      end
    end
  end
end

In the full test suite everything above the expect statement is set using lets or set in before blocks. I tried to distil it down to the smallest options and the test is still failing.

Question

I was expecting

stub_request(:post, "#{ENV['API_PROXY']}/api/checks").
  to_return(status: [500, "Internal Server Error"])

to always return a 500 status response, but it is returning 200.

Were my expectations correct? Is this how webmocks should be called?


Solution

  • you need to add the query params to the stub_request method, you can change it to be like this

    stub_request(:post, "#{ENV['API_PROXY']}/api/checks")
      .with(query: {api_check: api_params})
      .to_return(status: [500, "Internal Server Error"])