[rspec-users] State Based vs. Behaviour Based Spec/Testing

Scott Taylor mailing_lists at railsnewbie.com
Sun Mar 25 03:08:04 EDT 2007

On Mar 25, 2007, at 2:40 AM, Pat Maddox wrote:

> On 3/25/07, Scott Taylor <mailing_lists at railsnewbie.com> wrote:
>> On Mar 25, 2007, at 2:25 AM, Pat Maddox wrote:
>>> On 3/24/07, Scott Taylor <mailing_lists at railsnewbie.com> wrote:
>>>> 1.  Should you test protected and private methods in your specs?
>>> No.  You're specifying the behavior of an object as seen by the
>>> outside world.  Of course protected and private methods aren't
>>> available to the world, so why would you need to test them?  When
>>> you're doing state-based testing, just call a method and then verify
>>> that it returns the expected value or leaves your object in an
>>> expected state.
>> How about if your writing code that is *only* meant to be reused?
>> E.g., you are writing some class which is only meant to be derived
>> from (ruby metaprogramming - Spec'ing rails would be a good example)?
> I'm not sure what you mean, to tell you the truth.  Would you mind
> showing an example of some code that you want to spec but aren't sure
> how?

I had in mind a rails generic crud controller.  The basic gist of it  
is would be one class which had a series of private class methods.   
These methods could be called in any class which derived from this  
class, which would then set certain instance variables and instance  
methods for use in the class.

A good example is a typical rails controller, or class:

class Person < ActiveRecord::Base
   has_many :posts

If you say something like:

@person = Person.find(:first_name => "Scott", :last_name => "Taylor)


The first line will find the first person in the database that  
matches "Scott Taylor."  The second will find all posts associated  
with Scott Taylor.

What do you think the ActiveRecord::Base class is going to look  
like?  It's going to have a private class method named "has_many"  
which excepts a string or symbol as a parameter.  This will then  
create an instance method in the derived class.  In this example,  
that instance method would "posts".  (For simplicity sake I've left  
out or changed some details of all the other things rails does).

ActiveRecord::Base will never be used on its own, only as a class  
which is derived from.

So how would ActiveRecord::Base be spec'ed out for this example?

I haven't posted my code example because what I was trying to achieve  
was implemented by someone else already, and I decided to abandon the  
attempt.  I've noticed that they have a spec directory in their  
project, so I'll have to check out how they've spec'ed out their class.



More information about the rspec-users mailing list