[rspec-users] Mocking Models in Controller Specs...

Scott Taylor mailing_lists at railsnewbie.com
Mon May 26 16:29:56 EDT 2008


On May 26, 2008, at 3:52 PM, Mark Dodwell wrote:

> I find myself doing this kind of thing a lot in Controller Specs:
>
>      @vacancy = mock_model(Vacancy)
>      @vacancy.stub!(:reference)
>      @vacancy.stub!(:title)
>      @vacancy.stub!(:created_at)
>      @vacancy.stub!(:updated_at)
>      @vacancy.stub!(:body)
>      @vacancy.stub!(:contract)
>      @vacancy.stub!(:location)
>      @vacancy.stub!(:salary)
>      @vacancy.stub!(:benefits)
>      @vacancy.stub!(:start_date)
>      @vacancy.stub!(:duration)
>
> I have to stub each of these methods so that the form renders  
> correctly
> (as I am using integrate_views). This just feels *way* too much code  
> and
> effort to do this. I have a spec for one controller (which just does
> plain old CRUD) that is over 300 LOC -- this seems a bit nuts to me  
> when
> the controller is only 50 LOC.
>
> Does anybody have any suggestions on how to avoid this or perhaps I am
> doing something wrong!?

I would highly suggest using :null_object => true in view specs (or  
controller specs with integrate_views):

mock_model(MyARModel, :null_object => true, :to_s => "foobar")

stubbing :to_s is also important in view specs.  If you don't stub  
to_s, to_s will be called on the mock object, and you'll get invalid  
XHTML (see this ticket: http://rspec.lighthouseapp.com/projects/5645/tickets/230-mock-null_object-true-doesn-t-play-nice-with-html)

Scott



More information about the rspec-users mailing list