Last active
December 3, 2017 15:32
-
-
Save stevo/31c821fd62379aebc82d61976cc1c8e6 to your computer and use it in GitHub Desktop.
Testing private methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Poor specs | |
# ========== | |
describe CloseOrder do | |
# Testing #call using partial double of object being tested | |
# looks unnatural and feels as a duplication | |
describe '#call' do | |
it do | |
order = create(:order) | |
service = CloseOrder.new(order) | |
allow(service).to receive(:send_notification) | |
service.call | |
expect(service).to have_received(:send_notification) | |
end | |
end | |
describe '#send_notification' do | |
it 'delivers order closed notification to customer' do | |
order = create(:order, customer_email: '[email protected]') | |
service = CloseOrder.new(order) | |
expect { | |
service.send(:send_notification) # We are forced to use #send to test private method | |
}.to change { ActionMailer::Base.deliveries.count }.by(1) | |
notification = ActionMailer::Base.deliveries.last | |
expect(notification).to have_attributes(subject: 'Order closed!', recipients: ['[email protected]']) | |
end | |
end | |
end | |
# Good specs | |
# ========== | |
describe CloseOrder do | |
describe '#call' do | |
it 'delivers order closed notification to customer' do | |
order = create(:order, customer_email: '[email protected]') | |
service = CloseOrder.new(order) | |
expect { | |
service.call | |
}.to change { ActionMailer::Base.deliveries.count }.by(1) | |
notification = ActionMailer::Base.deliveries.last | |
expect(notification).to have_attributes(subject: 'Order closed!', recipients: ['[email protected]']) | |
end | |
end | |
end | |
# Implementation | |
# ============== | |
class CloseOrder | |
def initialize(order) | |
@order = order | |
end | |
def call | |
send_notification | |
end | |
private | |
def send_notification | |
OrderMailer.order_closed_notification(@order).deliver_now | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment