2012-02-08 131 views

回答

6

有測試accepts_nested_attributes_for方便shoulda寶石的匹配,但你提到你不想用其他寶石。所以,只使用Rspec,這個想法是設置attributes散列,該散列將包括所需的Tester屬性和稱爲skill_attributes的嵌套散列,其將包括所需的Skill屬性;然後將它傳遞到Testercreate方法,看看它是否改變Testers的數量和Skills的數量。類似的東西:

class Tester < Person 
    has_one :company 
    accepts_nested_attributes_for :skill 
    # lets say tester only has name required; 
    # don't forget to add :skill to attr_accessible 
    attr_accessible :name, :skill 
    ....................... 
end 

你的檢查:

# spec/models/tester_spec.rb 
...... 
describe "creating Tester with valid attributes and nested Skill attributes" do 
    before(:each) do 
    # let's say skill has languages and experience attributes required 
    # you can also get attributes differently, e.g. factory 
    @attrs = {name: "Tester Testov", skill_attributes: {languages: "Ruby, Python", experience: "3 years"}} 
    end 

    it "should change the number of Testers by 1" do 
     lambda do 
     Tester.create(@attrs) 
     end.should change(Tester, :count).by(1) 
    end 

    it "should change the number of Skills by 1" do 
     lambda do 
     Tester.create(@attrs) 
     end.should change(Skills, :count).by(1) 
    end 
end 

哈希語法可能會有所不同。另外,如果您有任何唯一性驗證,請確保在每次測試之前動態生成@attrs哈希。 乾杯,隊友。