2011-02-22 26 views
6

我進入rspec這些天,試圖讓我的模型更精確和準確。有些事情對我來說還是有點奇怪,所以我認爲如果有人能夠澄清,這將會很好。Rspec Rails - 名稱應該是有效的 - 一些澄清

比方說,我有一個用戶模型。這個有一個:名字。該名稱應該在4..15個字符之間(這是次要目標,首先它必須存在)。所以現在我在想:以確保這種情況發生的方式來測試它的最佳方式是什麼?要測試一個用戶必須有一個名字,我寫了這樣的東西:

describe User do 
    let(:user) { User.new(:name => 'lele') } 

    it "is not valid without a name" do 
     user.name.should == 'lele' 
    end 
end 

現在,我不太確定,這完成了我想要的。在我看來,我實際上正在用這個測試Rails。此外,如果我想檢查一個名稱不能超過15個字符且小於4個,那麼這怎麼可能被整合?

編輯:

也許這樣比較好?

describe User do 
    let(:user) { User.new(:name => 'lele') } 

    it "is not valid without a name" do 
     user.name.should_not be_empty 
    end 

end 

回答

5

我用這樣的方式:

describe User do 

    it "should have name" do 
    lambda{User.create! :name => nil}.should raise_error 
    end 

    it "is not valid when the name is longer than 15 characters" do 
    lambda{User.create! :name => "im a very looooooooong name"}.should raise_error 
    end 

    it "is not valid when the name is shorter than 4 characters" do 
    lambda{User.create! :name => "Tom"}.should raise_error 
    end  
end 
+1

請注意,所有.create!方法撞擊數據庫並使測試速度降低了100倍。您可以使用@Dylan Markow的以下說明避免緩慢並仍然檢查有效性。 – aaandre 2013-11-06 00:00:09

15

你可能尋找be_valid匹配:

describe User do 
    let(:user) { User.new(:name => 'lele') } 

    it "is valid with a name" do 
    user.should be_valid 
    end 

    it "is not valid without a name" do 
    user.name = nil 
    user.should_not be_valid 
    end 
end 
2

我想測試實際的錯誤消息驗證:

require 'spec_helper' 

describe User do 
    let (:user) { User.new } 

    it "is invalid without a name" do 
    user.valid? 
    user.errors[:name].should include("can't be blank") 
    end 

    it "is invalid when less than 4 characters" do 
    user.name = "Foo" 
    user.valid? 
    user.errors[:name].should include("is too short (minimum is 4 characters)") 
    end 

    it "is invalid when greater than 15 characters" do 
    user.name = "A very, very, very long name" 
    user.valid? 
    user.errors[:name].should include("is too long (maximum is 15 characters)") 
    end 

end 

使用建立具有有效屬性的對象的工廠也很有幫助,您可以一次使其中的一個無效,以便進行測試。

+0

非常有趣的做法,thanx – Spyros 2011-02-23 00:00:33

0

我會使用類似的東西來此

class User < ActiveRecord::Base 
    validates_presence_of :name 
    validates_length_of :name, :in => 4..15 
end 


describe User do 
    it "validates presence of name" do 
    user = User.new 
    user.valid?.should be_false 
    user.name = "valid name" 
    user.valid?.should be_true 
    end 

    it "validates length of name in 4..15" do 
    user = User.new 
    user.name = "123" 
    user.valid?.should be_false 
    user.name = "123456789" 
    user.valid?.should be_false 
    user.name = "valid name" 
    user.valid?.should be_true 
    end 
end 

最引人注目的是,我使用的活動記錄驗證了這兩個條件。在我的例子中,我不依賴錯誤字符串。在測試驗證行爲的示例中,沒有理由觸及數據庫,所以我不這樣做。在每個示例中,我測試對象在有效和無效時的行爲。