[rspec-users] is there a convention for testing that a record exists?

David Chelimsky dchelimsky at gmail.com
Tue Nov 29 22:19:48 EST 2011


On Nov 29, 2011, at 2:32 PM, Patrick J. Collins wrote:

> In the app I am working on, there are a lot of observers for various models
> which call Event.create! to log stuff...  So within a particular example,
> various records might be created in order to test behavior-- and this would
> result in several events being created.
> 
> So say, I have a spec that does:
> 
> it "creates an event when sharing a post" do
>  user = create_user                # this will make an event record of type "user created"
>  post = create_post(:user => user) # this will make an event record of type "post created"
>  post.share!
> 
>  # check to see that Event has a "post shared" event
> end
> 
> ...
> 
> Normally I would just do Event.last.event_type.should == "post shared"
> 
> However, if the Event model has it's default_scope set to order records in a
> certain way, that test might fail.
> 
> So I could do:
> 
> Event.unscoped.last.event_type.should == "post shared"
> 
> But then I begin thinking maybe it should be more like this:
> 
> it "creates an event when sharing a post" do
>  Event.exists?(:event_type => "post shared").should be_false
> 
>  user = create_user # this will make an event record of type "user created"
>  post = create_post(:user => user) # this will make an event record of type "post created"
>  post.share!
> 
>  Event.exists?(:event_type => "post shared").should be_true
> end
> 
> ...  I'm just not sure what's the best way to go, and if there's a convention
> for this sort of thing?


I'm not aware of a solid convention for this. I tend to avoid the pairing of the 1st and last lines of the 2nd example.

Are the events associated to the posts at all? If so you could specify post.events.map(&:event_type).should include("post shared") or some such.


More information about the rspec-users mailing list