RSpec期望改变:
it "should increment the count" do
expect{Foo.bar}.to change{Counter.count}.by 1
end
Run Code Online (Sandbox Code Playgroud)
有没有办法预期两个表的变化?
expect{Foo.bar}.to change{Counter.count}.by 1
and change{AnotherCounter.count}.by 1
Run Code Online (Sandbox Code Playgroud)
Geo*_*ann 76
我更喜欢这种语法(rspec 3或更高版本):
it "should increment the counters" do
expect { Foo.bar }.to change { Counter, :count }.by(1).and \
change { AnotherCounter, :count }.by(1)
end
Run Code Online (Sandbox Code Playgroud)
是的,这是一个地方的两个断言,但因为块只执行了一次,它可以加速测试.
编辑:在.and避免语法错误后添加反斜杠
Fre*_*ore 22
尝试使用@ MichaelJohnston的解决方案时出现语法错误; 这是最终为我工作的形式:
it "should increment the counters" do
expect { Foo.bar }.to change { Counter.count }.by(1)
.and change { AnotherCounter.count }.by(1)
end
Run Code Online (Sandbox Code Playgroud)
我应该提到我正在使用ruby 2.2.2p95 - 我不知道这个版本在解析中是否有一些微妙的变化导致我得到错误,看起来这个线程中没有其他人有这个问题.
Chr*_*ald 20
这应该是两个测试.RSpec最佳实践要求每次测试一个断言.
describe "#bar" do
subject { lambda { Foo.bar } }
it { should change { Counter.count }.by 1 }
it { should change { AnotherCounter.count }.by 1 }
end
Run Code Online (Sandbox Code Playgroud)
Uri*_*Uri 11
如果您不想使用之前建议的基于速记/上下文的方法,您也可以执行类似的操作,但要注意它会运行两次预期,因此可能不适合所有测试.
it "should increment the count" do
expectation = expect { Foo.bar }
expectation.to change { Counter.count }.by 1
expectation.to change { AnotherCounter.count }.by 1
end
Run Code Online (Sandbox Code Playgroud)
Georg Ladermann 的语法更好,但不起作用。测试多个值更改的方法是组合数组中的值。否则,只有最后的更改断言才会决定测试。
我是这样做的:
it "should increment the counters" do
expect { Foo.bar }.to change { [Counter.count, AnotherCounter.count] }.by([1,1])
end
Run Code Online (Sandbox Code Playgroud)
这与“.to”函数完美配合。