Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding assert_difference in Ruby on Rails

Could anyone please explain what this test code does? :

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 can't understand it even though I read the documentation.

Thanks!

like image 872
never_had_a_name Avatar asked Jul 27 '10 21:07

never_had_a_name


2 Answers

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
like image 157
Greg Campbell Avatar answered Oct 21 '22 01:10

Greg Campbell


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)

like image 30
Mitch Dempsey Avatar answered Oct 21 '22 01:10

Mitch Dempsey