Je le test suivant, avec deux blocs presque identiques. Maintenant, je cherche des moyens de refactoriser cela proprement.rspec refactoring?
Le 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
Comme vous pouvez le dire, deux blocs de code identiques, chacun pour un distributeur différent, D1 et D2 (dans notre projet, ils ont des noms plus significatifs :)) - et maintenant i besoin d'ajouter un troisième distributeur. Comment vais-je à ce sujet?
Je peux boucler sur un tableau contenant les parties changeantes (dans ce cas: nom du distributeur et contenu du message). Mais puis-je aussi changer le nom du test?
Quelles sont les meilleures approches ici? Est-il possible de faire une sorte de modèle de test, où vous pouvez remplir certaines valeurs et l'exécuter?
Ceci est une très bonne suggestion pour supprimer le code en double! – nathanvda