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

ruby-on-rails – Rails测试和摩卡:如何存根特定模型 – 条件an

发布时间:2020-12-17 03:08:37 所属栏目:百科 来源:网络整理
导读:我想只存储一个特定的模型,但不仅仅是一个特定的对象,而不是每个实例 例如.给定类’Person’,其属性为’name'(字符串)和’cool'(布尔值).我们有两种型号: person_bill: name: bill cool: falseperson_steve: name: steve cool: false 现在我想要只是史蒂夫,
我想只存储一个特定的模型,但不仅仅是一个特定的对象,而不是每个实例

例如.给定类’Person’,其属性为’name'(字符串)和’cool'(布尔值).我们有两种型号:

person_bill:
   name: bill
   cool: false

person_steve:
   name: steve
   cool: false

现在我想要只是史蒂夫,这工作正常:

p1 = people(:person_steve)
p1.stubs(:cool? => true)
assert p1.cool? #works

但是,如果我再次从DB加载Model,它不会:

p1 = people(:person_steve)
p1.stubs(:cool? => true)
p1 = Person.find_by_name p1.name
assert p1.cool? #fails!!

这有效,但也影响比尔,不应该:

Person.any_instance.stubs(:cool? => true)
 assert people(:person_bill).cool? #doesn't fails although it should

那么我怎么能只是史蒂夫存根,但无论如何?是否有条件的any_instance之类的

Person.any_instance { |p| p.name == 'Steve' }.stubs(:cool? => true)

提前致谢!

解决方法

为什么不直接生成对象的方法?

Person.stubs( :find_by_name ).
       returns( stub(:cool? => true) )

我认为这是正确的(而且简单的)答案.我很确定没有像any_instance语法那样的东西.您可能会在序列语法中找到有用的东西:

> http://mocha.rubyforge.org/classes/Mocha/API.html#M000005

你能再举一个你想要的例子吗?祝好运!

(编辑:李大同)

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

    推荐文章
      热点阅读