'Rails RSpec use mock instead of stub
I've got a lib which deals with some external API. The details are irrelevant, everything works well:
module SampleApi
extend self
def fetch_mm_recommender(email:)
handle_response(client.get("#{Sample.test_uri}/api/v1/mm_recommender", email: email))
end
private
def handle_response(response)
return parse_body(response) if response.success?
Rails.logger.error "Request failed with code: #{response.status}, message: #{response.reason_phrase}"
response.reason_phrase
end
def parse_body(response)
JSON.parse(response.body)
end
def client
@client ||= HttpHelper.new(with_cert: true)
end
end
I've made RSpec test for that:
describe '#fetch_mm_recommender' do
subject(:fetch_physician) { described_class.fetch_mm_recommender(email: email) }
let(:email) { '[email protected]' }
context 'when email exists in SAMPLE' do
before do
stub_request(:get, %r{/api/v1/mm_recommender})
.to_return(status: 200,
body: sample_response,
headers: {})
end
it 'fetch user data' do
expect(fetch_physician).to be_present
expect(fetch_physician).to eq(JSON.parse(sample_response))
end
end
Shouldn't I use mock rather than stub? Would there be any benefit to this? if so, what should such a test look like?
[EDIT]
context 'when email does not exist' do
let(:email) { '[email protected]' }
let(:sample_response) { 'Not found'.to_json }
before do
stub_request(:get, %r{/api/v1/mm_recommender})
.to_return(status: 404,
body: sample_response,
headers: {})
allow(Rails.logger).to receive(:error)
end
it 'does not retrieve data' do
expect(fetch_physician).to eq('')
expect(Rails.logger).to have_received(:error).with('Request failed with code: 404, message: ')
end
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
