2012-08-30 44 views
0

我花了大部分時間閱讀RSpec的各種文章和演練。雖然我學到了很多東西,但我仍然有點頭腦冷靜,而且仍然很有用。 RSpec很有表現力,這很好,但它似乎使初學者很難編寫簡潔的測試。DRY-ify RSpec測試

我可以看到自己做了很多事情的一件事情是測試每個邊緣案例的兩邊,以及單個變量的單個或多個有效值。目前,我有以下這樣的事情:

context "when physical address line 1 is too short" do 
    before { @contact.physical_addr_line_1 = "1" } 

    it { should_not be_valid } 
    specify { @contact.save.should_not be_true } 
end 

context "when physical address line 1 is too long" do 
    before { @contact.physical_addr_line_1 = "1"*111 } 

    it { should_not be_valid } 
    specify { @contact.save.should_not be_true } 
end 

context "when physical address line 1 is valid length" do 
    before { @contact.physical_addr_line_1 = "11111" } 

    it { should be_valid } 
    specify { @contact.save.should be_true } 
end 

有沒有一種重構的方法來清理它了一下?我想在其中添加更多的有效值(目前只根據該長度進行檢查),並對多個其他地址行變量執行相同的一組測試。效率,可讀性和可維護性對我來說都非常重要,因此有關如何更好地進行此類測試或任何推薦閱讀的建議將值得讚賞。

回答

0

你可以把它弄乾這個。我認爲還要讓它更具可讀性。

塊之前定義有效屬性一次,在一個:

before(:each) do 
    @attr = #attributes hash 
end 

context "validations" do 

    it "should not accept attribute that is too long" do 
    long_string = "a" * unacceptable number 
    Model.new(@attr.merge(attribute: long_string)).should_not be_valid 
    end 

    it "should not accept attribute that is too short" do 
    short_string = "a" * unacceptable number 
    Model.new(@attr.merge(attribute: short_string)).should_not be_valid 
    end 
end 

此外,早該寶石是優異的。 https://github.com/thoughtbot/shoulda

它將使寫這樣的測試:

it {should ensure_length_of(:attribute).is_at_least(n).is_at_most(n)} 
+0

這早該寶石將是一個巨大的節省時間,感謝。這些例子也有很大幫助。 – bdx