この状況では、3 つのことをまとめて確認したいと思います。
あなたが本当に望んでいるのは、特定の条件下でのこれらの動作を記述し、その動作が仕様を満たしていることを確認することだと私は主張します。それは、物事が一緒に起こることを意味するかもしれません。または、ある条件セットでのみ発生し、他の条件では発生しないこと、または例外によりすべてが元の状態にロールバックされることを意味する場合があります。
すべてのアサーションを 1 つのテストで処理する魔法はありませんが、高速化は別です。(フルスタック テストでよくあるように) 深刻なパフォーマンスの低下に直面していない限り、テストごとに 1 つのアサーションを使用する方がはるかに優れています。
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
「ハッピー パス」の 3 つのテストすべてに合格した場合、最初のシステム状態はいずれの場合も同じだったため、それらはすべて「一緒に発生」しました。
ただし、何か問題が発生したときに、システムが元の状態に戻らないようにする必要もあります。複数のアサーションを使用すると、これが期待どおりに機能すること、およびテストが失敗したときに正確にどのように失敗したかを簡単に確認できます。