在这种情况下,我想一起检查 3 件事:
我认为您真正想要的是在特定条件下描述这些事物的行为,从而确保行为符合您的规范。这可能意味着事情会一起发生;或者这可能意味着某些事情只在一组条件下发生而不在其他条件下发生,或者异常导致一切都回滚到其原始状态。
在一个测试中包含所有断言并没有什么神奇之处,除了让事情变得更快。除非您面临严重的性能损失(在全栈测试中经常发生),否则每次测试使用一个断言要好得多。
RSpec 可以直接提取测试设置阶段,以便为每个示例重复它:
class Account
attr_accessor :balance
def transfer(to_account, amount)
self.debit!(amount)
to_account.credit!(amount)
Audit.create!(message: "Transferred #{amount} from #{self.number} to #{to_account.number}."
rescue SomethingBadError
# undo all of our hard work
end
end
describe Account do
context "when a transfer is made to another account" do
let(:other_account} { other_account }
context "and the subject account has sufficient funds" do
subject { account_with_beaucoup_bucks }
it "debits the subject account"
it "credits the other account"
it "creates an Audit entry"
end
context "and the subject account is overdrawn" do
subject { overdrawn_account }
it "does not debit the subject account"
it "does not credit the other account"
it "creates an Audit entry" # to show the attempted transfer failed
end
end
end
如果“快乐路径”中的所有三个测试都通过了,那么它们都“一起发生”,因为在每种情况下初始系统状态都是相同的。
但是您还需要确保在出现问题时不会发生任何事情,并且系统会恢复到其原始状态。拥有多个断言可以很容易地看到它按预期工作,并且当测试失败时,它们究竟是如何失败的。