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

Jim Gay jim at saturnflyer.com
Fri Jun 27 22:55:49 EDT 2008

On Jun 27, 2008, at 10:07 PM, David Chelimsky wrote:
> 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.

Good point. Being a newbie I sometimes find myself where I *think* I'm  
doing it well, but find out that it's not quite that good afterall.

> 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.

Thanks for the response. Perhaps I'm over thinking things. I agree  
that "project.should have_one(:owner)" is unnecessary.

Somewhere the ideas get mangled for me.
Suppose a simple spec like this:

Project "should not be valid without a name"
Owner "should not be valid without a name"

How do you spec that the Owner may have 0 or more projects?

Owner "should be valid with 0 projects"
Owner "should be valid with more than 0 projects"

Or would you combine them

Owner "should have 0 or more projects"

Or should I not care at all about that and just specify that a Project  
"should not be valid without an owner"?

More information about the rspec-users mailing list