Understanding assert_difference in Ruby on Rails

后端 未结 4 1284
日久生厌
日久生厌 2021-02-13 02:43

Could anyone please explain what this test code does? :

assert_difference(\'Post.count\') do
    post :create, :post => { :title => \'Hi\', :body => \'T         


        
相关标签:
4条回答
  • 2021-02-13 03:34

    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

    0 讨论(0)
  • 2021-02-13 03:34

    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 讨论(0)
  • 2021-02-13 03:40

    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
    
    0 讨论(0)
  • 2021-02-13 03:43

    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)

    0 讨论(0)
提交回复
热议问题