2013-03-04 53 views
0

進出口新的軌道:) 我嘗試運行我的第一次測試。爲什麼這個測試通過?用戶名應至少有2個字符,我的用戶名更多,它仍然通過測試。RSpec的與色器件

user.rb:

validates :username, :length => { :minimum => 2 } 

user_spec.rb

require 'spec_helper' 

describe User do 

before do 
    @user = User.new(username: "Example User", email: "[email protected]", 
        password: "foobar", password_confirmation: "foobar") 
end 

describe "when name is not present" do 
    before { @user.username="aaaahfghg" } 
    it { should_not be_valid } end 

end 
+1

我沒有看到用戶名長度測試。另外驗證是最少2個,超過2個則通過驗證。 – 2013-03-04 19:22:01

回答

0
describe "when name is not present" do 
before { @user.username = "aaaahfghg" } 
it { should_not be_valid } 
end 

首先,你的描述塊被測試爲錯誤的東西。如果你想測試「名稱不存在」你應該設置:

@ user.username =「」 #makes用戶名空。

但是,爲了檢查用戶名是否爲空,您應該添加validates :username, presence: true。雖然你可能並不需要它,因爲你有一個{ minimum: 2 }驗證

現在,@user.username = "aaaahf"#編寫的一個更好的辦法是「一個」 * 5爲例,它創建一個5的= AAAAA的字符串。

,指出你的用戶名是超過200個字符,以便您的驗證是好的,{ minimum: 2 }測試應該通過。

如果你想確保用戶名是超過200個字符,然後

@user.username = 'a' 

希望可以幫助。

0

這條線:

it { should_not be_valid } 

採用implicit subject。 RSpec的自動創建類User,然後就可以在it塊內使用隱含的一個實例。但是你的測試會創建另一個實例並將其指定給@user - 這兩個實例不一樣。

如果你想使用隱式主題,你可以這樣做:

subject { User.new(args) } 
before { subject.username = "aaaahfghg" } 
it { should_not be_valid }