2011-12-30 35 views
1

這是我的驗證測試,我想找到最好的方式來編寫模型規格,特別是驗證。但是我在下面的代碼中遇到了問題。rspec測試模型驗證與主題 - 錯誤

require 'spec_helper' 

describe Ad, :focus do 
    let(:ad) { Ad.sham!(:build) } 

    specify { ad.should be_valid } 

    it "not creates a new instane given a invalid attribute" do 
    ad = Ad.new 
    ad.should_not be_valid 
    end 

    [:title, :category_id, :email, :ad_content, :name, :price].each do |attr| 
    it "should require a #{attr}" do 
     subject.errors[attr].should include("blank") 
    end 
    end  
end 

當我運行這個天賦我收到此錯誤:

5) Ad should require a name 
    Failure/Error: subject.errors[attr].should include("blank") 
     expected [] to include "blank" 
     Diff: 
     @@ -1,2 +1,2 @@ 
     -blank 
     +[] 
    # ./spec/model/ad_spec.rb:15:in `block (3 levels) in <top (required)>' 

回答

4

這裏的問題是,你沒有檢查錯誤之前調用在例如valid?。你在前面的例子中(間接)調用它,但不是你斷言有錯誤的那個。

正確的方法是這樣的:

[:title, :category_id, :email, :ad_content, :name, :price].each do |attr| 
    it "should require a #{attr}" do 
    subject.valid? 
    subject.errors[attr].should include("blank") 
    end 
end 
+0

再次感謝雷達:) – tomekfranek 2011-12-30 01:26:09