加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 使用Rspec在单元测试中测试“accepts_nested_attributes

发布时间:2020-12-17 03:02:07 所属栏目:百科 来源:网络整理
导读:我是rails和测试模型的新手.我的模型类是这样的: class Tester Person has_one :company accepts_nested_attributes_for :skill end 而且我想使用rspec和任何其他gem测试“accepts_nested_attributes_for:skill”.我怎么能做到这一点? 解决方法 有方便的s
我是rails和测试模型的新手.我的模型类是这样的:

class Tester < Person
  has_one :company
  accepts_nested_attributes_for :skill   
end

而且我想使用rspec和任何其他gem测试“accepts_nested_attributes_for:skill”.我怎么能做到这一点?

解决方法

有方便的shoulda gem matcher用于测试accepts_nested_attributes_for,但是你提到你不想使用其他宝石.因此,仅使用Rspec,我们的想法是设置包含所需Tester属性的属性哈希值和包含所需技能属性的名为skill_attributes的嵌套哈希值;然后将其传递给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

你的测试:

# 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哈希.队友的欢呼声.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读