Limit the amount of messages you send to objects

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the testing category.

Last Updated: 2024-11-23

Imagine you interacted with the user object with these 2-calls:

user.set_paid_through_date(1.year.from_now)
user.save!

To mock this, you'd need two stubs.

user = stub
paid_through_stub = stub
allow(user).to receive(:set_paid_through_date) { paid_through_stub }
allow(paid_through_stub).to receive(:save) { true }

Compare this approach to the following code which collapses the setting and saving into one method:

# user.rb

def pay_through(date)
  self.set_paid_through_date(date)
  self.save!
end

Now the caller is simplified

user.pay_through(1.year.from_now)

And the tests become much simpler as a result:

user = stub
allow(user).to receive(:pay_through) { true }

Lesson

To create good, easily tested designs, limit the amount of messages that you send to objects.