2

I don't understand how to setup webmock (or any stubbing library) to stub only specific requests to a particular url (www.example.com).

I am doing Cucumber tests on a browser and I want to allow connection to any site except for those requests I want to stub.

For my particular case, I want to stub the access to www.example.com/article/:article_id and deliver a HTML file of the page I had previously downloaded.

Following this link and other questions

# Gemfile
gem 'webmock'

# features/support/webmock.rb
require 'webmock/cucumber'

My Cucumber env file

# features/env.rb
# Allow all server connections by default
WebMock.allow_net_connect!

Before('@stub-example.com') do 
  stub_request(:get, 'https://www.example.com').to_rack(FakeExampleDotCom)
end

I am currently stuck at this stage, because the Stub isn't working and my test tries to connect to the real website. I suppose WebMock.allow_net_connect! disables any stub. I cannot just disable_net_connect! since I want to authorize every website (and not just localhost) and only "blacklist" www.example.com and stub it. How can I do that ?

FYI : My Sinatra app that serves the HTML file

class FakeExampleDotCom < Sinatra::Base
  get 'article/:article_id' do
    html_response 200, "#{params[:article_id]}_article.html"
  end

  private

  # Returns the HTML file corresponding to the article
  def html_response(response_code, file_name)
    content_type :html
    status response_code
    File.open(Rails.root.join('features', 'assets', file_name)).read
  end
end
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164
  • have you tried using [vcr gem](https://github.com/vcr/vcr) ? although, it records and later serves responses for specific spec examples rather than calls to specific addresses – Tomasz Giba Mar 17 '17 at 15:14
  • Yes I'm going to use VCR in the future, but there seems to be a lot of setup issues (managing secrets, hiding passwords, etc.) that are likely to require a lot of time. I want to see if I can have something working with a simple saved HTML file (that I can easily manipulate to remove data or inject data I want). – Cyril Duchon-Doris Mar 17 '17 at 16:28
  • I don't think you're right that `allow_net_connect!` disables stubs. This example gives the impression that it doesn't: https://github.com/bblimke/webmock#real-requests-to-network-can-be-allowed-or-disabled Could the problem be that you include `https://` in the stubbed hosts? None of the webmock examples seem to include the protocol, so try leaving it off: `stub_request(:get, 'www.example.com').to_rack(FakeExampleDotCom)` – Henrik N Mar 17 '17 at 22:07
  • Or might it be that you're stubbing https but perhaps the test makes a http request: http://stackoverflow.com/a/21369031/6962 – Henrik N Mar 17 '17 at 22:12

0 Answers0