Ruby 测试;接受“U嵌套”属性“U为”;使用Rspec进行单元测试
我不熟悉rails和测试模型。我的模型课是这样的:Ruby 测试;接受“U嵌套”属性“U为”;使用Rspec进行单元测试,ruby,ruby-on-rails-3,unit-testing,testing,rspec,Ruby,Ruby On Rails 3,Unit Testing,Testing,Rspec,我不熟悉rails和测试模型。我的模型课是这样的: class Tester < Person has_one :company accepts_nested_attributes_for :skill end 类测试员
class Tester < Person
has_one :company
accepts_nested_attributes_for :skill
end
类测试员
我想使用rspec测试“accepts\u nested\u attributes\u for:skill”,而不使用任何其他gem。如何实现这一点?应该有一个方便的
gem matchers,用于测试接受的嵌套属性,但您提到不想使用其他gem。因此,仅使用Rspec,想法是设置属性
散列,其中包括必需的Tester
属性和嵌套散列,称为skill\u attributes
,其中包括必需的skill
属性;然后将其传递到Tester
的create
方法中,查看它是否会更改测试人员的数量
和技能的数量
。诸如此类:
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
散列语法可能不同。此外,如果您有任何唯一性验证,请确保在每次测试之前动态生成@attrs
哈希。
干杯,伙计
# 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