开发者

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_f开发者_运维技巧riend, :email => 'friend@example.com'
end

I can't understand it even though I read the documentation.

Thanks!


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)


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜