2012-02-08 134 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哈希。 干杯,队友。