[rspec-users] Example for attr_accessible?

Wincent Colaiuta win at wincent.com
Wed Oct 17 05:39:27 EDT 2007

El 17/10/2007, a las 7:26, "Pat Maddox" <pergesu at gmail.com> escribió:

> Well, you'll find differing opinions on this.  Every time I've done
> validations I've written a spec that actually exercises the behavior.
> For example
> class Person < ActiveRecord::Base
>   validates_presence_of :name
> end
> describe Person do
>   it "should not be valid without a name" do
>     p = Person.new
>     p.should_not be_valid
>     p.errors.on(:name).should == "can't be blank"
>   end
> end
> As far as I'm concerned, that's specifying the behavior.  A person
> without a name is not valid, and it results in an error message on
> name.  Doing it the way we've discussed in this thread is ugly and
> stupid, imo.

I agree that you'll find many opinions on this. My personal take is  
that you should be testing the behaviour, not testing that the  
"validates..." method was called.

Why? Because while this is fine for a simple validation like  
validates_presence_of, it can fall down for complex validations  
with :on, :if, and other clauses. The problem is that it is fairly  
easy to write a complex validation that doesn't actually do what you  
think it does. Testing that you set it up gives you very little in  
that case; you should be testing that it *does* what you think it  
does. You are not testing ActiveRecord in this case (it's well  
tested); you are testing that your use of ActiveRecord gives you the  
desired behaviour. And as has already been pointed out, you can write  
a custom matcher to make such oft-used specs easy to write. My own  
take on this is here:


Compare this with attr_accesible. That's much simpler; it takes a  
list of symbols. It is much harder to make a mistake. In that case I  
think it's fine to mock the call and just check that your code does  
the attr_accessible call. But having said that, seeing as testing the  
behaviour directly is so simple (just try mass assigning and see if  
it worked or not) I just test the behaviour anyway and forget about  
the mock+load trick.


More information about the rspec-users mailing list