在使用Rspec进行单元测试时测试“accep_nested_attributes_for”
问题描述:
我是rails和测试模型的新手。我的模型类是这样的:在使用Rspec进行单元测试时测试“accep_nested_attributes_for”
class Tester < Person
has_one :company
accepts_nested_attributes_for :skill
end
我想要做的“accepts_nested_attributes_for:技能”测试使用RSpec的与任何其他宝石。我怎样才能做到这一点?
答
有测试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
哈希。 干杯,队友。