代码之家  ›  专栏  ›  技术社区  ›  Michael Durrant

ruby-如何使用由另一个被清除的方法填充的属性

  •  0
  • Michael Durrant  · 技术社区  · 11 年前

    我在测试中用

    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
    

    但问题是 @单词 通常由 字典.load_system_directory 方法,但我不想使用它,因为它有90k条记录,但如果没有它 File.open(words_file).each {|word| @words << word} 我的 @单词 属性未填充。

    如果我愿意

    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}
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   Rustam Gasanov    11 年前

    如果 contains_word 是一个 Dictionary 方法,您可以这样做

    dictionary.instance_variable_set(:@words, your_words_array)
    

    More info 关于 instance_variable_set .