テストを準備から切り離して、テストをよりクリーンにします。これは、この 1 つの長いテストの例では次のことを意味します。
# create an account factory with trait account_type
# create manager factory for the account
# 5 people factories opt-in to that account
# 1 person then opts out
# a manager creates and sends a broadcast
--> no asserts until now, because that is test preparation
これを入れてbefore(:all)
、別のテストを行うことができます:
before(:all) do
# no asserts here, just the steps to do it
# create an account factory with trait account_type
# create manager factory for the account
# 5 people factories opt-in to that account
# 1 person then opts out
# a manager creates and sends a broadcast
# so in the end you got:
@people = ...
@manager = ...
@opt-ins = ...
@opt-out = ...
@broadcast = ...
end
it "should not send the message to the opt-out" do
# the one opt-out does not get the message
end
it "should send the message to the four opt-ins" do
# the four opt-ins get the message
end
it "should have the right message format" do
# verify the format of the message
end
さらに、before(:all)
別のテストでの手順もテストする必要があります。
it "should be able to create an account with account_type" do
# create an account factory with trait account_type
# assert it worked
end
it "should be able to create a manager for an account" do
# create an account factory with trait account_type
# no assertion that it worked (that is tested before)
# create manager factory for the account
# assert manager got correctly created
end
it "should be able to opt-in to accounts" do
# create an account factory with trait account_type
# no assertion that it worked (that is tested before)
# 5 people factories opt-in to that account
# assert that it worked
end
it "should be able to opt-in to accounts" do
# create an account factory with trait account_type
# 5 people factories opt-in to that account
# 1 person then opts out
# assert that it worked
end
少しコードの重複がありますが、それによってテストがシンプルになり、読みやすくなります。
最後に、テストを整理するには、shared_context
. したがって、異なるテスト/ファイルで同じものを準備する必要がある場合は、それらを次のように含めますshared_context
。
# spec/contexts/big_message_broadcast.rb
shared_context "big message broadcast" do
before(:all) do
# no asserts here, just the steps to do it
# create an account factory with trait account_type
# create manager factory for the account
# 5 people factories opt-in to that account
# 1 person then opts out
# a manager creates and sends a broadcast
# so in the end you got:
@people = ...
@manager = ...
@opt-ins = ...
@opt-out = ...
@broadcast = ...
end
end
# spec/.../some_spec.rb
describe "long opt-in opt-out scenario" do
include_context 'big message broadcast'
it "should not send the message to the opt-out" do
...
end
...
end
そうすれば、好きな場所で簡単include_context 'big message broadcast'
に準備できます。