gpt4 book ai didi

ruby - 使用 Rspec 在单元测试中测试 "accepts_nested_attributes_for"

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:12 25 4
gpt4 key购买 nike

我是 Rails 和测试模型的新手。我的模型类是这样的:

class Tester < Person
has_one :company
accepts_nested_attributes_for :skill
end

而且我想在不使用任何其他 gem 的情况下使用 rspec 对“accepts_nested_attributes_for :skill”进行测试。我怎样才能做到这一点?

最佳答案

有方便的 shoulda gem 匹配器用于测试 accepts_nested_attributes_for,但您提到您不想使用其他 gem。因此,仅使用 Rspec,想法是设置包含所需 Tester 属性的 attributes 散列和包含所需 skill_attributes 的嵌套散列 技能属性;然后传入Testercreate方法,看是否改变了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 哈希。干杯,伙计。

关于ruby - 使用 Rspec 在单元测试中测试 "accepts_nested_attributes_for",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com