我会将测试与准备测试分开以使其更清洁。这意味着在您的示例中,这是一项长期测试:
# 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'
它来准备任何你喜欢的地方。