Andreas Vöst
1 year
Claus-Theodor Riegg
2 years
Moritz Kraus
2 years
Claus-Theodor Riegg
2 years
Stefan Xenopol
2 years

Mock Net::HTTP requests with RSpec

Posted . Visible to the public.

We often do some HTTP requests to fetch the data we want to check for certain criteria. Testing this in the real world can be slow and inconvenient, when we aren't able to connect to the endpoint from our notebook.

Fixture JSON file:

{
  "categories":[],
   "created_at":"2020-01-05 13:42:21.795084",
   "icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png",
   "id":"02e1usSQT_yO1AahT6meRg",
   "updated_at":"2020-01-05 13:42:21.795084",
   "url":"https://api.chucknorris.io/jokes/02e1usSQT_yO1AahT6meRg",
   "value":"Paul McCartney eats a vegan diet all the time -- except when he eats in the presence of Chuck Norris."
}
# spec/chuck_norris_spec.rb
require 'webmock/rspec'
require 'net/https'

describe "ChuckNorrisJoke" do
  before do
    stub_request(:any, 'https://api.chucknorris.io/jokes/random' )
      .to_return(body: File.open('spec/fixtures/chuck-norris.json'))
  end

  it 'is funny' do
    uri = URI('https://api.chucknorris.io/jokes/random')
    res = Net::HTTP.get_response(uri)
    expect(res.body).to include('Paul')
  end
end
rspec  spec/chuck_norris_spec.rb
.

Finished in 0.00759 seconds (files took 0.49565 seconds to load)
1 example, 0 failures
Moritz Kraus
Last edit
Moritz Kraus
Keywords
chuck, norris
License
Source code in this card is licensed under the MIT License.