kun*_*nnu 4 ruby testing unit-testing rspec ruby-on-rails-3
我是rails和测试模型的新手.我的模型类是这样的:
class Tester < Person
has_one :company
accepts_nested_attributes_for :skill
end
Run Code Online (Sandbox Code Playgroud)
而且我想使用rspec和任何其他gem测试"accepts_nested_attributes_for:skill".我怎么能做到这一点?
有方便的shoulda宝石匹配器进行测试accepts_nested_attributes_for,但你提到你不想使用其他宝石.因此,使用Rspec的只是,这个想法是设置attributes散列将包括所需的Tester属性,并呼吁嵌套散列skill_attributes,其中将包括所需Skill的属性; 然后将其传递给create方法Tester,并查看它是否改变了数量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
Run Code Online (Sandbox Code Playgroud)
你的测试:
# 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
Run Code Online (Sandbox Code Playgroud)
散列语法可能不同.此外,如果您有任何唯一性验证,请确保@attrs在每次测试之前动态生成哈希.队友的欢呼声.