我有两个例子,但我觉得它们里面的大部分代码都是一样的。然而,它们有点不同(记录略有不同,第二个也有另外一个断言)。我仍然是测试的初学者,所以在我前进时只是寻找一些技巧。我正在测试一个rake任务。这是我的代码:
it 'leaves one billing info for each order' do
order = FactoryGirl.create(:order)
FactoryGirl.create_list(:billing_info, 2, order_id: order.id)
expect(BillingInfo.all.count).to eq(2)
run_rake_task
expect(BillingInfo.all.count).to eq(1)
end
it 'keeps the billing info with trevance information' do
order = FactoryGirl.create(:order)
FactoryGirl.create(:billing_info, order_id: order.id, complete_trevance_message: nil, trevance_attempts: nil)
FactoryGirl.create(:billing_info, order_id: order.id, complete_trevance_message: "303 -- Processor Decline", trevance_attempts: 1)
expect(BillingInfo.all.count).to eq(2)
run_rake_task
expect(BillingInfo.all.count).to eq(1)
expect(BillingInfo.first.complete_trevance_message).to eq("303 -- Processor Decline")
end
如你所见,它们非常相似。可以将这些分成两个这样的吗?或者有更好的方法吗?
答案 0 :(得分:1)
在我看来,DRY并不总是测试中最好的规则。这通常意味着你必须在方法中隐藏一些代码,这样就更难以阅读等等。所以我没有太大变化,但有一些事情可以用更简单的方式完成。
context "billing rake task"
let(:order) { FactoryGirl.create(:order) }
it 'leaves one billing info for each order' do
FactoryGirl.create_list(:billing_info, 2, order_id: order.id)
expect { run_rake_task }.to change { BillingInfo.count }.by(-1)
end
it 'keeps the billing info with trevance information' do
FactoryGirl.create(:billing_info, order_id: order.id, complete_trevance_message: nil, trevance_attempts: nil)
FactoryGirl.create(:billing_info, order_id: order.id, complete_trevance_message: "303 -- Processor Decline", trevance_attempts: 1)
expect { run_rake_task }.to change { BillingInfo.count }.by(-1)
expect(BillingInfo.first.complete_trevance_message).to eq("303 -- Processor Decline")
end
end
请注意,这会稍微改变一下规格,因此您不会检查计数是否从2正好变为1,而是更改为1。我认为这里更好,但我不能确定,因为我不太清楚你的应用程序。
答案 1 :(得分:0)
我会重构这样的事情:
let(:order) { FactoryGirl.create(:order) }
describe "description here" do
before do
FactoryGirl.create_list(:billing_info, 2, order_id: order.id)
end
it 'leaves one billing info for each order' do
expect(BillingInfo.all.count).to eq(2)
run_rake_task
expect(BillingInfo.all.count).to eq(1)
end
end
describe "description here" do
before do
FactoryGirl.create(:billing_info, order_id: order.id, complete_trevance_message: nil, trevance_attempts: nil)
FactoryGirl.create(:billing_info, order_id: order.id, complete_trevance_message: "303 -- Processor Decline", trevance_attempts: 1)
end
it 'keeps the billing info with trevance information' do
expect(BillingInfo.all.count).to eq(2)
run_rake_task
expect(BillingInfo.all.count).to eq(1)
expect(BillingInfo.first.complete_trevance_message).to eq("303 -- Processor Decline")
end
end
before
挂钩将在您需要时为您提供更大的灵活性。