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

Patrick J. Collins patrick at collinatorstudios.com
Tue Nov 29 15:32:44 EST 2011


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?

Patrick J. Collins
http://collinatorstudios.com



More information about the rspec-users mailing list