您的位置:首页 > 编程语言 > Ruby

Ruby on rails Web开发单元测试部分断言

2014-03-05 16:56 211 查看
学习Ruby on rails时编写单元测试时整理的常用的断言。当编写单元测试时,下面这些断言很可能会对你有所帮助。
1.

assert(boolean,message)


如果 boolean 参数值为 false 或 nil,则断言失败。例子如下:

assert(User.find_by_name("dave" ), "user 'dave' is missing" )


2.

assert_equal(expected, actual,message)
assert_not_equal(expected, actual,message)


除非 expected 参数与 actual 参数相等/不等,否则断言失败。例子如下:

assert_equal(3, Product.count)
assert_not_equal(0, User.count, "no users in database" )


3.

assert_nil(object,message)
assert_not_nil(object,message)


除非 object 参数是/不是 nil,否则断言失败。例子如下:

assert_nil(User.find_by_name("willard" )
assert_not_nil(User.find_by_name("henry" )


4.

assert_in_delta(expected_float, actual_float, delta,message)


除非两个浮点数之差的绝对值小于 delta 参数,否则断言失败。在判断浮点数 相等时应该尽量使

用此方法而不是 assert_equal(),因为浮点数是不精确的。例子如下:

assert_in_delta(1.33, line_item.discount, 0.005)


5.

assert_raise(Exception, ...,message) { block... }
assert_nothing_raised(Exception, ...,message) { block... }


除非代码块产生/不产生列举的异常之一,否则断言失败。例子如下:

assert_raise(ActiveRecord::RecordNotFound){Product.find(bad_id)}


6.

assert_match(pattern, string,message)
assert_no_match(pattern, string,message)


除非 string 参数与 pattern 参数指定的正则表达式匹配/不匹配,否则断言失败。如果 pattern参数是一个字符串,

则进行全文匹配,任何正则表达式元字符都不会被转义。例子如下:

assert_match(/flower/i, user.town)
assert_match("bang*flash" , user.company_name)


7.

assert_valid(activerecord_object)


除非参数提供的 ActiveRecord 对象合法(换句话说,通过校验),否则断言失失败,错误信息会被用作断言失败信息的一部分。例子如下:

user=Account.new(:name=>"dave",:email=>'secret@pragprog.com')
assert_valid(user)


8.

flunk(message)


无条件地失败。例子如下:

unless user.valid? || account.valid?
  flunk("One of user or account should be valid" )
end


Ruby 的单元测试框架还提供了别的一些断言,

不过那些断言在 Rails 应用的测试中就不太常用了,可以在 Test::Unit 的文档里找到所有的断言。

一些附加的功能测试断言:

1.

assert_dom_equal(expected_html, actual_html,message)
assert_dom_not_equal(expected_html, actual_html,message)


比较两个包含 HTML 的字符串。如果两者代表相同,不同的文档对象模型(DOM),则断言成功。简

单说来,这个断言就是对两个字符串进行规范化(normalize)处理,然后再进行比较。例子如下:
expected = "<html><body><h1>User Unknown</h1></body></html>"
assert_dom_equal(expected, @response.body)


2.
assert_response(type,message)


这个断言接收的参数是一个代表 HTTP 状态的数字,或者是下列符号中的一个——这些符号分别代

表了一个范围的应答代码(譬如说,:redirect 就代表了 300 —399 的所有代码)。

:success

:redirect

:missing

:error

例如:
assert_response :success
assert_response 200


3.
assert_redirected_to(options,message)


判断最后一个 action 中进行的重定向是否正确。你也可以传入一个字符串作为参数,该方法将把

重定向生成的 URL 与之进行比较。例子如下:

assert_redirected_to :controller => 'login'
assert_redirected_to :controller => 'login' , :action => 'index'
assert_redirected_to "http://my.host/index.html"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息