我刚刚开始使用RSpec和Rails深入到TDD中,我发现如果我正在测试一个应该是真的的方法,那么如果我使用expect(方法)而不是expect(方法).to be_true,测试就会工作。
it "is true" do
expect(subject).to be_true
#Works the same as...
expect(subject)
end是否有任何理由不使用expect而不使用.to,它会破坏测试还是不会捕捉到某些故障?只是想知道。
发布于 2014-03-28 21:33:54
你没有达到你认为的那样。expect(false)不会失败。expect(true)之所以成功,是因为什么都没有被测试。例如,如果您有以下规范:
describe "something" do
it "does something" do
false
puts expect(false)
# anything that evaluates to false
end
end当您运行rspec时,您会得到这样的结果:
#<RSpec::Expectations::ExpectationTarget:0x007ff0b35a28b8\>
.
Finished in 0.00061 seconds
1 example, 0 failures本质上,您没有断言任何内容,expect(subject)的计算结果为ExpectationTarget。
发布于 2014-03-28 19:17:17
我认为后者起作用是一种巧合。
每个expect语句都以某种方式计算为true或false。
例如
arr = ['a', 'b', 'c']
expect(arr).to include('a')将返回true,因为arr包含'a'。
因此,在您的示例中,expect(subject)和expect(subject).to be_true在某种程度上相当于以下内容:
bool = true
if bool
# Do something here
if bool == true
# Do something here长话短说,这并不重要,但出于可读性的考虑,我更喜欢expect(subject).to be_true。
https://stackoverflow.com/questions/22721084
复制相似问题