【问题标题】:Testing the "accepts_nested_attributes_for" in unit testing using Rspec使用 Rspec 在单元测试中测试“accepts_nested_attributes_for”
【发布时间】:2012-02-08 12:32:21
【问题描述】:
我是 Rails 和测试模型的新手。我的模型类是这样的:
class Tester < Person
has_one :company
accepts_nested_attributes_for :skill
end
我想使用 rspec 测试“accepts_nested_attributes_for :skill”,而不使用任何其他 gem。我怎样才能做到这一点?
【问题讨论】:
标签:
ruby
ruby-on-rails-3
unit-testing
testing
rspec
【解决方案1】:
有方便的shoulda gem 匹配器用于测试accepts_nested_attributes_for,但您提到您不想使用其他 gem。因此,仅使用 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 哈希。
干杯,伙计。