繁体   English   中英

在Ruby中扩展模块和测试类(或实例?)方法

[英]Extending modules and testing class (or instance?) methods in Ruby

Ruby的新手,谢谢您! 我在同一目录中有2个文件。 其中.rb =

module Where
  def self.where(hash = {})
    self.select do |fixture| #iterate over fixtures indexes |fixture| 
      hash.all?  do |key, value| #return true as long as hash exists
        value === fixture[key]
      end
    end
  end
end

和test.rb =

require 'minitest/autorun'
require './where.rb'

class WhereTest < Minitest::Test
  extend Where
  def setup
    @boris   = {:name => 'Boris The Blade', :quote => "Heavy is good. Heavy is reliable. If it doesn't work you can always hit them.", :title => 'Snatch', :rank => 4}
    @charles = {:name => 'Charles De Mar', :quote => 'Go that way, really fast. If something gets in your way, turn.', :title => 'Better Off Dead', :rank => 3}
    @wolf    = {:name => 'The Wolf', :quote => 'I think fast, I talk fast and I need you guys to act fast if you wanna get out of this', :title => 'Pulp Fiction', :rank => 4}
    @glen    = {:name => 'Glengarry Glen Ross', :quote => "Put. That coffee. Down. Coffee is for closers only.",  :title => "Blake", :rank => 5}

    @fixtures = [@boris, @charles, @wolf, @glen]
  end

  def test_where_with_exact_match
    assert_equal [@wolf], @fixtures.where(:name => 'The Wolf')
  end

  def test_where_with_partial_match
    assert_equal [@charles, @glen], @fixtures.where(:title => /^B.*/)
  end

  def test_where_with_mutliple_exact_results
    assert_equal [@boris, @wolf], @fixtures.where(:rank => 4)
  end

  def test_with_with_multiple_criteria
    assert_equal [@wolf], @fixtures.where(:rank => 4, :quote => /get/)
  end

  def test_with_chain_calls
    assert_equal [@charles], @fixtures.where(:quote => /if/i).where(:rank => 3)
  end
end

puts WhereTest

我所有的测试都说NoMethodError:#Array:0x000000027d6a20的未定义方法“ where”。

我不确定错误的含义。 我使用应使用的类方法创建了一个模块。 该模块的方法应可用于extend Where WhereTest类

该错误消息表示没有为数组定义此类方法时,您尝试在Array实例上调用where方法。

似乎您希望将where方法添加到Array类中(因为您将@fixtures.where@fixtures称为Array。但是,您是将其添加到WhereTest类中。

您将需要执行以下操作:

class Array
  extend Where
end

class WhereTest < Minitest::Test
  def setup
  ...

现在,您提供的代码还有其他问题(例如,修补核心类是危险的,通常强烈建议不要这样做)。 但这至少应该使您更接近要尝试的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM