[rspec-users] Should(not?) test associations (was: Dealing with dependent data)

David Chelimsky dchelimsky at gmail.com
Fri Jun 27 22:07:27 EDT 2008


On Jun 27, 2008, at 6:58 PM, Jim Gay wrote:

> I've been meaning to ask the list about this for a while now.
>
> I don't always use "should", but I've been trying to come up with a  
> standard way to approach the Rails has_one, has_many, etc. as  
> opposed to methods on the object such as name, description etc.
> What I mean is that I want to write specs so that I know if  
> something refers to an associated object or not, without resorting  
> to writing technically oriented specs that define implementation  
> rather than behavior.
> "project should have an owner" unfortunately doesn't let me know if  
> it's a method that returns a value, or a method that returns another  
> object.

An association does not want you to know that it's an association. It  
wants you to think of it as any other attribute. Why do you care what  
it IS? Focus on what it DOES.

> Does anyone have advice or experience in writing the specs to  
> provide that kind of information?
>
> I hope this isn't too much of a thread hijack.

We'll make a new thread then :)

My opinion is that attributes and associations are equally about  
structure, not behaviour. The fact that a project has an owner is not  
behaviour. The fact that the owner has an email address is not  
behaviour.

The facts that you can't save a project without an owner, and you  
can't save an owner without a valid email address are behaviour. And  
by setting expectations around those, the attributes and associations  
themselves are handled implicitly:

describe Project do
   it "should not be valid without an owner" do
     Project.new(:owner => nil).should_not be_valid
   end
end

Watch that fail saying that Project does not respond to 'owner='  
method. Add a migration and an association. Now it fails saying that  
it was valid. Add the validation and watch the example pass. That's  
TDD (yes, starting with a T).

Any time I have a an attribute or an association that I *think* is  
supposed to be on a model, I try to think of what might be interesting  
about that attribute or association and set expectations about that.

There are many who believe that we should have examples like  
"project.should have_one(:owner)." I can't say that those people are  
wrong if doing that is adding value to their process and helping them  
deliver quality software. For me, personally, it's just unnecessary  
noise that adds maintenance burden later when things move around. And  
it definitely ain't behaviour.

Cheers,
David


More information about the rspec-users mailing list