[rspec-users] Four Question From an RSpec Baby - Give me something to chew

Mark Wilden mark at mwilden.com
Wed Aug 27 15:25:01 EDT 2008

On Wed, Aug 27, 2008 at 10:20 AM, Lake Denman <lists at ruby-forum.com> wrote:

> def upgrade(payment)
>    transaction do
>      payment.user_id = self.id
>      payment.payment_type = Payment::SUBSCRIPTION_PAYMENT_TYPE
>      return false unless (payment.save and payment.external_id)
>      self.subscription_id = payment.external_id
>      self.payment_id = payment.id
>      self.member = true
>      self.member_since = AppLib.today_utc
>      self.save
>      return true
>    end
>  end
> 2.) Is it wrong to access multiple objects (user and payment in my
> example) in a Unit Test example?

I'll disagree with Pat and say yes (in general). A unit test/spec should
exercise a unit, which I usually consider to end at the class boundary.

For example, this code relies on Payment#save being correct. If it's buggy
(or doesn't exist), a spec of this User method could very well fail, even if
there is nothing wrong with the payment method. That's not a unit test, in
my view. I would mock out the payment in a spec for this method to ensure
that save and external_id are called, but not rely on them being correct (or
even existing). In a spec for Payment#save, I would make sure that it sets
external_id correctly (if that's what it's supposed to do). The combination
of the two specs would be enough (in my view) to document and test the
behavior of these classes.

I won't rattle on about the benefits of unit tests, other than to say that
by testing only one unit at a time, you reduce the odds of that horrible
moment when you change one line of code and 36 tests in 18 other spec files
fail. All that said, pragmatism trumps purity, and if you're willing to spec
two "units" in one "unit test," and it makes your life easier to do so, then
go for it. :)

The other thing I would say is that mocking and stubbing are powerful tools
that you should add to your arsenal as soon as possible. I've had several
coworkers who resisted using them, only to finally achieve that "aha!"
moment later. Your tests get easier to write, and they're less brittle to

I might add that I learned much of this from working on a prior codebase of
Pat's. That doesn't mean I couldn't have got it all wrong, of course. :)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20080827/53e0b8b7/attachment.html>

More information about the rspec-users mailing list