Skip to content

Instantly share code, notes, and snippets.

@stevo
Last active December 3, 2017 15:29
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/977d3799dda3c109890d8e4659bdf3ff to your computer and use it in GitHub Desktop.
Save stevo/977d3799dda3c109890d8e4659bdf3ff to your computer and use it in GitHub Desktop.
Stubbing framework methods
# Poor specs
# ==========
describe PurgeDomainUsers do
describe '.call' do
# Test does not leave any freedom in implementation
it 'removes all users with email matching domain provided' do
users = instance_double(:users_collection)
allow(User).to receive(:where) { users }
allow(users).to receive(:destroy_all)
PurgeDomainUsers.call(domain: 'stark.com')
expect(User).to have_received(:where).with('email ILIKE :domain_query', domain_query: "%@stark.com"))
expect(users).to have_received(:destroy_all)
end
end
end
# Good specs
# ==========
describe PurgeDomainUsers do
describe '.call' do
it 'removes all users with email matching domain provided' do
tony = create(:user, email: 'tony@stark.dev')
create(:user, email: 'bruce@wayne.dev')
howard = create(:user, email: 'howard@stark.dev')
create(:user, email: 'peter@parker.dev')
expect {
PurgeDomainUsers.call(domain: 'stark.dev')
}.to change { User.count }.from(4).to(2)
expect { tony.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect { howard.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
# Implementation
# ==============
class PurgeDomainUsers
def self.call(domain:)
User.
where('email ILIKE :domain_query', domain_query: "%@#{domain}").
destroy_all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment