[英]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.