[rspec-users] Cucumber - stub! or mock?

Matt Wynne matt at mattwynne.net
Tue Sep 16 02:49:31 EDT 2008

On 15 Sep 2008, at 21:14, Tim Glen wrote:

> Hey all,
> I've got some code that I (mostly) inherited. It essentially has a  
> couple of AR class methods that look for a specific record by id:
> class Project < ActiveRecord::Base
>   class << self
>     def specific_project
>       @another_specific_project ||= Project.find(10) if  
> Project.exists?(10)
>     end
>     def another_specific_project
>       @specific_project ||= Project.find(11) if Project.exists?(11)
>     end
>   end
> end
> Typically, when I've specced this code (or more accurately, code  
> that uses it), I've stubbed out those methods to return a mocked  
> model. Lately, I've started using cucumber and adding stories for  
> areas we're adding features to or finding regressions in. From what  
> I can tell, I can't stub or mock anything from within cucumber step  
> files. Realizing that the pattern is a bit of code smell, I feel  
> like I have two directions I could go:
> 1. Is there a way to stub out the model to return some fixture-type  
> records?
> 2. Does anyone have an idea as to how we could refactor this into a  
> better pattern? Those 2 "projects" are pretty specific to the  
> production data and will "never be edited," but it still doesn't  
> make me comfortable.

If those objects are built into your system and will never, ever  
change, I would consider storing their definition in the code rather  
than in the database anyway.


That would get around your issues with the pristine test database  
being different to the production / development database, and IMO  
more clearly communicates to future developers that these objects are  

Of course it depends on how many of them there are, whether you have  
a use case for editing them etc, but it's worth thinking about.

Alternatively you could call the migrations that insert this stock  
data (presumably you have some) from your spec pre-requisites.


In case you wondered: The opinions expressed in this email are my own  
and do not necessarily reflect the views of any former, current or  
future employers of mine.

More information about the rspec-users mailing list