【问题标题】:ruby - how to use an attributes that's populated by another method that's stubbed outruby - 如何使用由另一种方法填充的属性
【发布时间】:2014-03-15 22:38:10
【问题描述】:

我有一些测试,我用 stub 删除了一个对象属性

dictionary.stub(:words).and_return
(%w{cat,dog,fish,plane,rock,dig,dug,cut,cuts,put,puts,putting,ruby,use,GO,IT})

这样我就不必使用Dictionary.load_system_dictionary 方法来填充@words,我可以只删除words 方法。

现在我想测试另一个名为contains_word(word)的方法:

def contains_word(word)
  @words.map(&:upcase).join.include?(word.upcase)
end

但问题是 @words 通常由 Dictionary.load_system_dictionary 方法填充,但我不想使用它,因为它有 90k 条记录,但没有它是 File.open(words_file).each {|word| @words << word} 我的 @words attr 不是正在填充。

如果我这样做了

dictionary.load_system_dictionary 

对于真正的字典,测试通过
但是如果我用

替换它
dictionary.stub(:words).and_return
(%w{cat,dog,fish,plane,rock,dig,dug,cut,cuts,put,puts,puttingzaq1,ruby,use,GO,IT})

我明白了

Failure/Error: expect(dictionary.contains_word('IT')).to be true

expected #<TrueClass:2> => true
got #<FalseClass:0> => false

btw 字典最初设置为

let(:dictionary) {Dictionary.new}

【问题讨论】:

    标签: ruby rspec stub


    【解决方案1】:

    如果contains_wordDictionary 方法,你可以这样做

    dictionary.instance_variable_set(:@words, your_words_array)
    

    More info 关于instance_variable_set

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多