Search code examples
ruby-on-railsrubyrspeccapybarawebmock

Web mock does not work with redirect_to in Rails controller


My controller has this piece of code:

class MyController < App::BaseController
  def login
    redirect_to 'https://some.api.com/auth?params'
  end
end

Of course I don't want to be redirected to external website in tests. So I decided to add webmock gem and add:

WebMock.disable_net_connect!(allow_localhost: true)

To my spec_helper.rb.

Inside my feature tests I have:

  scenario 'stubbing external api' do
    visit '/connect_to_some_external_api'
    stub_request(:any, /https:\/\/some.api.com\/auth\//)
      .to_return(status: 200, body: 'DUPA. A nawet DUPA123')
    # this works as intended  ->Net::HTTP.get('https://some.api.com/auth/')
    click_link 'Get me to MyController#login'
  end

When I call Net::HTTP.get('https://some.api.com/auth/') I get response "DUPA. A nawet DUPA123". Which is cool! That means stub_request works.

The issue is when user clicks link to MyController#get where redirect takes place. It doesn't stub request and just let browser to be redirected to external application.

Is it possible to stub request which comes from controller's redirect_to? If yes, then how?


Solution

  • In feature tests the requests come from the browser, so you can't mock requests on the server with stub_request. You should verify the redirect in a controller/request spec. If you really need to test this in a feature test the most flexible solution is to use a programmable proxy like puffing-billy