我在一个类中定义了一个方法,如下所示:
def show_benefits_section?
yield if has_any_context?
end
我想为此编写一个测试,到目前为止,我已经有了(可以使用):
test_class.stub(:has_any_context?, true) do
test_class.show_benefits_section? do |show_section=true|
assert_equal(show_section, true)
end
end
我只是不确定这是否是测试该方法的最佳方法... 以及我如何测试阴性条件?
任何帮助将不胜感激!
答案 0 :(得分:1)
首先,您的代码没有进行任何测试,无论如何它总是成功。试试这个成功的例子来证明这一点:
[1].each do |first=nil, second=2|
assert_equal(1, first)
assert_equal(2, second)
end
让我exaplain;变量second
始终为2,无论如何,因为方法each
不会对其产生影响,并且默认值设置为2。相反,{{ 1}}被忽略,beucase nil
传递了一个对象。
这是一个改进的代码段,用于测试您的情况。
它同时测试块返回true和false的情况,以及first
是true和false的情况。我不认为有一种通用的方法可以具体验证该块产生的值。相反,您可以验证方法返回的结果。
each
请注意,您的方法has_any_context?
返回从块返回的所有内容。上面的示例也通过给出一个随机值5来对其进行测试。按照Ruby的约定,方法名称以'?'结尾。应该返回true或false(尽管有# Test: :has_any_context? == true
test_class.stub(:has_any_context?, true) do
# Test: a block must be given.
assert_raises(LocalJumpError) { test_class.show_benefits_section? }
# Test: yield
[true, false, 5].each do |tobe|
# If 5 is given, 5 is returned.
ret = test_class.show_benefits_section? do
tobe
end
assert_equal(tobe, ret)
end
end
# Test: :has_any_context? == false
test_class.stub(:has_any_context?, false) do
ret = test_class.show_benefits_section?{true}
assert_nil(ret)
end
之类的异常)。如果要遵循约定,最简单的方法可能是将相关部分重写为
show_benefits_section?
完成此修改后,您可以确认上述测试现在失败。