2014-02-26 56 views
1

我一直試圖成爲一個合適的TDD傢伙。我已經在我的模型上設置了Rspec,FactoryGirl和一些基本測試。所有這些測試都驗證了我的Plantask模型的存在。我開始在Rails中測試,並且我不確定我的測試

我已經將工廠移到了前一個塊,這是一些小的重構,但由於我是新來測試,我想就如何改進我的測試提供一些建議。我還沒有足夠的經驗知道他們是否真的是「幹」。

在我的模型:

驗證:AREA_ID,存在:真#添加等。

我的測試:

require 'spec_helper' 

describe Plantask do 
    before(:each) do 
     @plantask = FactoryGirl.create(:plantask) 
    end 

    it "is valid with valid attributes" do 
     @plantask.should be_valid 
    end 

    it "is invalid without an area" do 
     @plantask.area_id = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without equipment" do 
     @plantask.equipment_id = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without a part" do 
     @plantask.part_id = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without a description" do 
     @plantask.description = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without a datatype" do 
     @plantask.datatype_id = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without an assignment" do 
     @plantask.assigned = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without an associate" do 
     @plantask.associate_id = nil 
     @plantask.should_not be_valid 
    end 

    it "is invalid without a number" do 
     @plantask.number = nil 
     @plantask.should_not be_valid 
    end 

end 

好吧,謝謝你們。現在我有這個,它更緊湊。很酷。

require 'spec_helper' 

describe Plantask do 

subject (:plantask) { FactoryGirl.create(:plantask) } 

    it { should validate_presence_of(:area_id) } 
    it { should validate_presence_of(:equipment_id) } 
    it { should validate_presence_of(:part_id) } 
    it { should validate_presence_of(:description) } 
    it { should validate_presence_of(:datatype_id) } 
    it { should validate_presence_of(:assigned) } 
    it { should validate_presence_of(:associate_id) } 
    it { should validate_presence_of(:procedure_id) } 
    it { should validate_presence_of(:recurrence) } 
    it { should validate_presence_of(:number) } 

    it { should be_valid } 
end 

回答

0

對於這種測試,我建議您使用shoulda-matchers gem,它可以幫助您清理代碼。

這將是這樣的:

it { should validate_presence_of(:area_id) } 
it { should validate_presence_of(:equipment_id) } 
... 
相關問題