Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stubbing library methods
# Poor specs
# ==========
# Test focus is divided between how library is used and and what is the expected behavior of tested class
describe ImportInvestigations do
describe '.call' do
it 'imports investigations to database' do
stub_const('ImportInvestigations::IMPORT_URL', 'http://gcpd.dev/investigations.json')
investigations_json = [
{ uid: '123', name: 'Joker: prison escape' },
{ uid: 'abc', name: 'Dr. Strange: arsony' }
].to_json
faraday_response = instance_double(Faraday::Response, body: investigations_json)
allow(Faraday).to receive(:get) { faraday_response }
expect {
ImportInvestigations.call
}.to change { Investigation.count }.from(0).to(2)
expect(Investigation.all).to include(
have_attributes(uid: '123', suspect_name: 'Joker', case_subject: 'prison escape'),
have_attributes(uid: 'abc', suspect_name: 'Dr. Strange', case_subject: 'arsony')
)
expect(Faraday).to have_received(:get).with('http://gcpd.dev/investigations.json')
end
end
end
# Better specs
# ============
# Test does not depend on any particular library being used
describe ImportInvestigations do
describe '.call' do
it 'imports investigations to database' do
stub_const('ImportInvestigations::IMPORT_URL', 'http://gcpd.dev/investigations.json')
investigations_json = [
{ uid: '123', name: 'Joker: prison escape' },
{ uid: 'abc', name: 'Dr. Strange: arsony' }
].to_json
stub_request(:get, "http://gcpd.dev/investigations.json").to_return(status: 200, body: investigations_json)
expect {
ImportInvestigations.call
}.to change { Investigation.count }.from(0).to(2)
expect(Investigation.all).to include(
have_attributes(uid: '123', suspect_name: 'Joker', case_subject: 'prison escape'),
have_attributes(uid: 'abc', suspect_name: 'Dr. Strange', case_subject: 'arsony')
)
end
end
end
# Best specs
# ==========
# Retrieval of records is abstracted to facade (that should get own set of tests)
describe ImportInvestigations do
describe '.call' do
it 'imports investigations to database' do
allow(GcpdWrapper).to receive(:get_investigations) {
[
double(uid: '123', suspect_name: 'Joker', case_subject: 'prison escape'),
double(uid: 'abc', suspect_name: 'Dr. Strange', case_subject: 'arsony')
]
}
expect {
ImportInvestigations.call
}.to change { Investigation.count }.from(0).to(2)
expect(Investigation.all).to include(
have_attributes(uid: '123', suspect_name: 'Joker', case_subject: 'prison escape'),
have_attributes(uid: 'abc', suspect_name: 'Dr. Strange', case_subject: 'arsony')
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.