有測試accepts_nested_attributes_for
方便shoulda
寶石的匹配,但你提到你不想用其他寶石。所以,只使用Rspec,這個想法是設置attributes
散列,該散列將包括所需的Tester
屬性和稱爲skill_attributes
的嵌套散列,其將包括所需的Skill
屬性;然後將它傳遞到Tester
的create
方法,看看它是否改變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
哈希。 乾杯,隊友。