1

My factory has an url field(used to fetch youtube embedded video):

factory :commercial do
    url 'https://www.youtube.com/watch?v=BTTygyxuGj8'
end

In my tests I tried to mock the request to youtube. I added following to my spec_helper:

require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)

RSpec.configure do |config|
  config.before(:suite) do
    mock_request
  end
end

def mock_request
  response = {
    author_name: 'Confreaks',
    # more attributes omitted ..
  }
  WebMock.stub_request(:get, /.*youtube.*/).
    to_return(status: 200, body: response.to_json, headers: {})
end

Isn't registering the webmock once in rspec config enough for the stub to be available through out the test suite? Why am I having to do this to my factory:

factory :commercial do
  url 'https://www.youtube.com/watch?v=BTTygyxuGj8'

  after(:build) do |commercial|
    mock_request
  end
end

Without the after(:build), I get following error:

Failure/Error: create(:commercial, WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: ...tells me about unregistered request to youtube and how I should stub it...

sonalkr132
  • 967
  • 1
  • 9
  • 25
  • did you ever figure this out? Seeing the same thing Now. Adding a validation on a model that hits an API endpoint. Webmock stub is not registering but it *does* work in feature specs that hit the same validation. – Jessie A. Young Mar 24 '16 at 23:41
  • Following this: https://robots.thoughtbot.com/how-to-stub-external-services-in-tests#sdctbs in spec_helper I changed `before(:suite)` to `before(:each)`. It doesn't seem to affect the test run time, however I don't feel very proud of the solution. – sonalkr132 Mar 25 '16 at 12:33
  • Hmm I already had mine set to `before(:each)`. For me, the solution was to remove the API request in the AR validation. I feel good about that because I think it was the right design decision, but I would like to understand the underlying *why* for the webmock in FG issue. More info here: https://github.com/18F/dolores-landingham-bot/pull/155#discussion_r57408981 – Jessie A. Young Mar 25 '16 at 18:48

1 Answers1

1

Does fill out headers in to_return call help?

.to_return(
  ...,
  headers: { "Content-Type" => "application/json; charset=utf-8" }
)

fill the hash with values provided from failure output.

Juanito Fatas
  • 9,419
  • 9
  • 46
  • 70