2012-02-02 24 views
1

如果你有,你是他們的存在測試屬性的列表,你具備以下條件:Rspec的測試:它{應的respond_to()}

before do 
    @attr = Employee.new(name: "One", 
         email: "[email protected]") 
end 

subject { @attr } 

it { should respond_to(:name) } 
it { should respond_to(:email) } 

it { should be_valid } 

你能不能再測試反向,即如果這些屬性是空白的使用:

it { should_not respond_to(:reverse, :blank) } 
it { should_not be_valid } 

我也嘗試了上面,但我不明白的問題,那麼好,甚至是閱讀this discussion後。

有誰知道如何使用相同的初始化來測試狀態,然後轉向並測試空白屬性?

+0

你究竟想要在這裏測試什麼?測試某些方法是否響應並測試該方法的返回值是否爲空是不相交的概念。 – 2012-02-02 21:04:42

回答

21

我想你誤會了respond_to確實在你的測試:如果你有對存在驗證這些測試將是一件好事。當你做

it { should respond_to(:name) } 

你聲稱@attr.respond_to(:name)回報true,這意味着該方法是存在,而不是它的返回值。如果你想測試有返回值,你可以這樣做:

its(:name){ should be_present } 

這將確保調用name方法的結果返回非假,非空值。然後,當您反向測試時

its(:name){ should_not be_present } 

您聲稱name方法返回空白。您必須爲第二次測試創建不同的設置,因爲您正在測試處於不同狀態的對象。

+0

謝謝@Emily ...我確實對respond_to有錯誤的理解。我需要做更多的閱讀和實驗來充實你的指導。當涉及:是否存在價值時,驗證是否符合要求? – thomasvermaak 2012-02-02 22:40:01

+1

關於Rspec的偉大之處在於測試這種類型的東西是多麼容易。當你在Rspec中調用'be_present'時,它在模型上調用'present?'。與'respond_to'調用'respond_to?'相同。然後您可以在IRB中輕鬆測試這些方法。但直接回答,'present?'返回除'''','''''''nil','false','[]'和'{}'以外的所有內容。 – Emily 2012-02-03 15:18:20

0

你的用戶對象上獨立測試應該更多這樣的:

it "should have an email attribute" do 
    @attr.should respond_to(:email) } 
end 

不過,如果你正在測試一個類,可能我建議沿着這爲您的測試線的東西更多:

before (:each) do 
    @attr = {name: "One", email: "[email protected]"} 
end 

那麼你的第一次測試,確保創建工作,像這樣:

it "should create a new instance given valid attributes" do 
    Employee.create!(@attr) 
end 

一旦you'v Ë確立的工作你就可以繼續你的其他測試,並有自動獲得像這樣創建的員工:

describe "Attributes and method tests" do 
    before (:each) do 
    @employee = Employee.create(@attr) 
    end 

    it "should have a name attribute" do 
    @employee.should respond_to(:name) 
    end 

    it "should have an email attribute" do 
    @employee.should respond_to(:email) } 
    end 

    # etc... (to test other attributes or methods) 
end 

要獲得關於扭轉測試,並指定這不是有效的,如果屬性是空白的問題,我會嘗試這樣的事情。

it "should not be valid with a blank email" do 
    Employee.new(@attr.merge(:email => '').should_not be_valid 
end 

it "should not be valid with a blank name" do 
    Employee.new(@attr.merge(:name => '').should_not be_valid 
end 
+0

這是主觀的,根本不回答問題。 – 2012-02-02 21:01:28

+0

對不起,我最初誤解了你的問題。以爲你在說你很難理解編寫測試的正確格式。我已經更新了我的答案。 – Batkins 2012-02-02 21:12:26

+0

嗯,這不是我的問題,但留下原來的東西仍然只是誤導主觀的絨毛,國際海事組織。 – 2012-02-02 21:14:47