I'm doing some RSPEC testing here.
If i have this method:
JSON.parse("https://test.com/return_json/reviews.json")
Then I can stub it RSPEC like:
test_reviews = {"reviews" => [{"data1" => "1", "data2"=> "2"}]}
allow(JSON).to receive(:parse).and_return(test_reviews.to_json)
But for this kind (with other method inside (to_uri
& read
)).
JSON.parse("https://test.com/return_json/reviews.json".to_uri.read)
I tried to used receive_message_chain
but no success.
Thanks in advance guys!
You code is not actually calling the url you. You need to make an http call and parse the body. I should probably look like this.
describe :ReviewsController
let(:uri) { URI('https://test.com/return_json/reviews.json') }
let(:reviews) { {"reviews" => [{"data1" => "1", "data2"=> "2"}]} }
before do
stub_request(:get, uri).
with(headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
to_return(status: 200, body: JSON.dump(reviews), headers: {})
end
it 'does whatever you want' do
response = Net::HTTP.get(uri)
expect(JSON.parse(response.body)['data1']).to eq('1') # or whatever you want to test
end
end
It's better explained here.