views:

29

answers:

2

Could anyone please explain what this test code do:

assert_difference('Post.count') do
    post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
end

and...

assert_difference 'ActionMailer::Base.deliveries.size', +1 do
  post :invite_friend, :email => '[email protected]'
end

I cant understand it even though I read the documentation.

Thanks!

+1  A: 

This is just checking to make sure that the number of objects for whatever type was specified has increased by 1. (It is an easy way to check to see that an object was added to the DB)

webdestroya
+1  A: 

assert_difference verifies that the result of evaluating its first argument (a String which can be passed to eval) changes by a certain amount after calling the block it was passed. The first example above could be "unrolled" to:

before = Post.count # technically, eval("Post.count")
post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
after = Post.count
assert_equal after, before + 1
Greg Campbell
but why does the 2nd example has +1 while the first one has no second parameter? what is the difference?
never_had_a_name
@fayer - I believe the default is `+1`. In the second example, they are just explicitly stating it.
webdestroya
Yep, the default is 1.
Greg Campbell