[rspec-users] When to stub_model?

Matt Wynne matt at mattwynne.net
Wed May 20 09:13:20 EDT 2009

On 20 May 2009, at 12:03, Lee wrote:

> Thanks Matt. Very helpful.
> I have tried out stub_model. The constructor of one of my models
> (Namespace) requires a mandatory :name attribute to be provided. So
> when I try to stub_model it - e.g. representative_namespace =
> stub_model(Namespace) - I get the following spec error.
> 1)
> RuntimeError in 'ContextsController POST create authenticated user
> should assign a representative namespace to the new context'
> A namespace must be assigned a valid name
> /Users/leelon/work/cbox/app/models/namespace.rb:696:in
> `raise_no_name_error'
> /Users/leelon/work/cbox/app/models/namespace.rb:688:in
> `get_processed_name'
> /Users/leelon/work/cbox/app/models/namespace.rb:643:in `set_name'
> /Users/leelon/work/cbox/app/models/namespace.rb:64:in `initialize'
> ./spec/controllers/contexts_controller_spec.rb:37:
> script/spec:10:
> Is there a way around this while still making :name a mandatory
> requirement of the constructor? I have tried stubbing out :name in the
> call to stub_model but this doesn't help:
> representative_namespace = stub_model(Namespace, :name => 'A name')

I can't remember if you can do that, to be honest. I think the hash of  
parameters to stub_model is used to set up stubs on the object - so  
they won't get passed to the constructor. Hopefully someone else on  
the list should be able to tell you if this is possible.

Matt Wynne

More information about the rspec-users mailing list