测试 Rails 常用断言方法整理

skpark1987 · 2015年07月19日 · 最后由 douxiance 回复于 2015年08月18日 · 5354 次阅读

assert assert_not assert_empty(obj, msg=nil) assert_equal(exp, act, msg=nil): 使用==进行判断 assert_same(exp, act, msg=nil): 使用 equal? assert_match(matcher, obj, msg=nil): 匹配正则表达式 exp =~ act assert_template(options = {}, message = nil)

# new模板
assert_template "new"
# 绝对路径的模板
assert_template %r{\Aadmin/posts/new\Z}
# 指定layout键
assert_template layout: 'admin'
assert_template layout: 'layouts/admin'
# _customer布局被渲染两次
assert_template partial: '_customer', count: 2
# 一个文件被渲染
assert_template file: "README.rdoc"

assert_difference(expression, difference=1, message=nil, &block)

#assert_difference ‘Article.count’ do
#assert_difference [ ‘Article.count’, ‘Post.count’ ], 2 do
#assert_difference ->{ Article.count }, 2 do
assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
    post :create, article: {}
end

assert_no_difference(expression, message=nil, &block) assert_redirected_to(options={}, message=nil)

# 指定controller及action
assert_redirected_to controller: "weblog", action: "index"
# 指定url
assert_redirected_to login_url
# @customer对象的show页面
assert_redirected_to @customer
# 满足正则表达式
assert_redirected_to %r(\Ahttp://example.org)

assert_response 指定 response 为下列中的一个 :success - Status code was in the 200-299 range :redirect - Status code was in the 300-399 range :missing - Status code was 404 :error - Status code was in the 500-599 range *assert_select(*args, &block) *

# 两个ol列表,里面包含4个li
assert_select "ol" do |elements|
  elements.each do |element|
    assert_select element, "li", 4
  end
end
assert_select "ol" do
  assert_select "li", 8
end

相等性测试 结构:assert_select "元素选择器", 判断参数 判断参数有以下的可能性 true 至少有一个元素 false 没有相应的元素 String/Regexp 至少有一个元素的文本内容与正则/字符串相匹配 Integer 有指定个数的元素 Range 存在范围内个数的元素 当执行多个相等性测试的时候,可以使用以下 hash 键 :text 筛选指定文本内容的元素 (字符串/正则) :html 筛选指定 HTML 内容的元素 (字符串/正则) :count 元素的个数与指定个数一致时返回 true :minimum 选择的元素的最小个数 :maximum 选择的元素的最大个数

# 至少有一个form元素
assert_select "form"
# form元素包含四个input元素
assert_select "form input", 4
# title为welcome
assert_select "title", "Welcome"
# title为Welcome,并且只有一个title元素
assert_select "title", {count: 1, text: "Welcome"},
    "Wrong title or more than one title element"
# 页面没有form元素
assert_select "form", false, "This page must contain no forms"
# 测试HTML元素及类结构
assert_select "body div.header ul.menu"
# 用正则判断指定li元素的ID是否符合要求
assert_select "ol>li#?", /item-\d+/
# form元素内的所有input元素的name有值
assert_select "form input" do
  assert_select "[name=?]", /.+/  # Not empty
end

这些断言方法一般用在什么场景,测试吗?

:plus1: 支持一下关注测试的 XD。

建议楼主稍微再整理一下

看着稍微有点痛苦。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号