Could anyone please explain what this test code does? :
assert_difference(\'Post.count\') do
post :create, :post => { :title => \'Hi\', :body => \'T
This assertion is to verify the certain/specified difference in the first argument. 1st argument should be a string i.e "Post.count". Second argument has a default value 1, you can specify other numbers also, even negetive numbers. for more details visit: http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html
This method is to verify that there is a numerical difference between first argument and the second argument. In Most cases first argument is a string which is like “Post.count”
and second argument is a block. In rails this is mostly used in functional testing to check if an object can be saved in the database. Logic is that before a new is object being saved, number of records in that particular table must be different from the number of records after the object is saved ( from 1 to be precise).
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
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)