理解Ruby on Rails中的assert_difference
谁有人可以解释这个测试代码的作用? :
assert_difference('Post.count') do post :create, :post => { :title => 'Hi', :body => 'This is my first post.'} end
和:
assert_difference 'ActionMailer::Base.deliveries.size', +1 do post :invite_friend, :email => 'friend@example.com' end
即使我阅读文档,我也无法理解。
谢谢!
assert_differencevalidation在调用传递的块之后,评估其第一个参数(可以传递给eval
的String)的结果会改变一定量。 上面的第一个例子可以“展开”到:
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
这只是检查以确保指定的任何类型的对象数量增加1.(这是一种检查以查看对象是否已添加到数据库的简单方法)
该断言用于validation第一个参数中的特定/指定差异。 第一个参数应该是一个字符串,即“Post.count”。 第二个参数的默认值为1,您也可以指定其他数字,甚至是negetive数字。 有关详细信息,请访问: http : //api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html
此方法用于validation第一个参数和第二个参数之间是否存在数字差异。 在大多数情况下,第一个参数是一个字符串,类似于“Post.count”
,第二个参数是一个块。 在rails中,这主要用于function测试,以检查对象是否可以保存在数据库中。 逻辑是在保存新对象之前,该特定表中的记录数必须与保存对象后的记录数不同(从1开始精确)。