I have the following test, with two almost identical blocks. Now i am looking for ways to refactor this cleanly.
The test:
context "with the d1 configuration" do
before (:each) do
# send a message
@envelope = Factory(:envelope, :destination => '32495xxxxxx', :message => 'Message sent by d1')
@distributor = Distributor.find_by_name(Distributor::D1)
@result = @envelope.send_to(@distributor)
end
it "should created a new sms-message" do
@envelope.sent_messages.size.should == 1
end
it "should have created one sms-message linked to the envelope and distributor" do
sms = @envelope.sent_messages.find_by_distributor_id(@distributor.id)
sms.should be_instance_of(SentMessage)
sms.external_message_id.should_not == nil
sms.sent_message_status_id.should == SentMessageStatus::IN_PROGRESS
end
it "should add a logline for the creation of the sms-message" do
@envelope.log_lines.size.should == 2
@envelope.log_lines.last.message.should =~ /^Sent message/
end
end
context "with the correct d2 configuration" do
before (:each) do
# send a message
@envelope = Factory(:envelope, :destination => '32495xxxxxx', :message => 'Message sent by d2')
@distributor = Distributor.find_by_name(Distributor::D2)
@result = @envelope.send_to(@distributor)
end
it "should created a new sms-message" do
@envelope.sent_messages.size.should == 1
end
it "should have created one sms-message linked to the envelope and distributor" do
sms = @envelope.sent_messages.find_by_distributor_id(@distributor.id)
sms.should be_instance_of(SentMessage)
sms.external_message_id.should_not == nil
sms.sent_message_status_id.should == SentMessageStatus::IN_PROGRESS
end
it "should add a logline for the creation of the sms-message" do
@envelope.log_lines.size.should == 2
@envelope.log_lines.last.message.should =~ /^Sent message/
end
end
As you can tell, two identical code blocks, each for a different distributor, D1 and D2 (in our project they have more meaningful names :)) -- and now i need to add a third distributor. How do i go about this?
I can loop over an array containing the changing parts (in this case: distributor-name and the message contents). But can i also change the test-name?
What are the best approaches here? Is it possible to make some kind of test-template, where you can fill in certain values and execute that?