Forum: RSpec is there a convention for testing that a record exists?

Posted by Patrick Collins (patrick99e99)
on 2011-11-29 22:07
(Received via mailing list)
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
Posted by David Chelimsky (Guest)
on 2011-11-30 04:55
(Received via mailing list)
On Nov 29, 2011, at 2:32 PM, Patrick J. Collins wrote:

>  post.share!
>
>  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.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.