[rspec-users] How to test update_attribute with mocha?

Matt Wynne matt at mattwynne.net
Thu May 14 02:53:33 EDT 2009

On 14 May 2009, at 05:01, Phlip wrote:

> anmaxp wrote:
>> I'm having sort of an issue here, I'm trying to test the update of  
>> the
>> last_login field upon login, here is my test
>>  it "assigns a new last_login timestamp" do
>>    User.expects(:update_attribute).at_least_once.returns(true)
> User.any_instance.expects(:update_attribute).with(:field, value).etc.
> An instance of User will itself call the .update_attribute. The  
> class won't call it.
> However, I can't think of a reason not to just write the record,  
> reload it, and check the fields. And a _functional_ test should not  
> care how the record got written (update_attribute, save, or  
> whatever). A unit test might care, but functional tests need a  
> little more float...

I've got a reason. You're coupling the tests for this simple little  
controller class to all the infrastructure and dependencies needed to  
write the record to the database and reload it again. As easy as Rails  
makes it for us to manage our database schemas, gratuitously  
introducing dependencies in your code like this is a bad habit to get  
into. It can lead to tests that are fragile to failing when code is  
changed far away from the place they're apparently testing. The tests  
also run slowly, which makes working on systems written like this  

I would argue that a true 'functional test'[1] would not even care  
that there is a controller class, and would be exercising the system  
via the user interface.


Matt Wynne

More information about the rspec-users mailing list