我的问题基于这个问题:rspec mocks: verify expectations in it "should" methods?以及这些指南:http://eggsonbread.com/2010/03/28/my-rspec-best-practices-and-tips/
那么,如果每个“它”块只有一个期望,那么如果我将模拟期望与价值预期相混合怎么办?
示例:
describe Foo, "#bar" do
before :all do
@baz = mock(Baz)
@foo = Foo.new(@baz)
end
it "should call waka on @baz" do
@baz.should_receive(:waka)
end
it "should not be empty afterwards" do
@foo.should_not be_empty
end
it "should not raise exceptions" do
lambda {@foo.bar}.should_not raise_exception # potentially with side effects?
end
after :all do
@foo.bar # won't work with the second expectation
end
end
我希望问题很清楚。有没有人有关于此案例的组织规范的经验?我做错了吗?
答案 0 :(得分:4)
每组的一个期望是一个建议,而不是一个硬性规则。你不应该疯狂地试图遵守它(在这种情况下,我认为使用after :all
块会有点疯狂。)
我也摆脱了before :all
而只是使用before :each
- 所有这些都可能偶尔导致令人困惑的状态错误。
describe Foo, "#bar" do
before do
@baz = mock(Baz)
@foo = Foo.new(@baz)
end
it "should call waka on @baz" do
@baz.should_receive(:waka)
@foo.bar
end
it "should not be empty afterwards" do
@foo.bar
@foo.should_not be_empty
end
it "should not raise exceptions" do
lambda { @foo.bar }.should_not raise_exception
end
end
实际上,你仍然只是为每组设定一个期望。