Skip to content

Instantly share code, notes, and snippets.

@stevo
Last active December 3, 2017 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevo/7c8f1185985a3fc48fe1ab5a3b6820ad to your computer and use it in GitHub Desktop.
Save stevo/7c8f1185985a3fc48fe1ab5a3b6820ad to your computer and use it in GitHub Desktop.
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