2015-05-09 53 views
0

我想寫一個模塊來通過我所有的測試。它看起來就像是一組哈希。我想弄清楚'哪裏'的邏輯是什麼?所以我可以嘗試寫一個模塊來通過所有的測試。ruby​​中的'where'行爲是什麼?

測試:

require 'test/unit' 

class WhereTest < Test::Unit::TestCase 
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 
+0

除非你使用Rails,否則它很可能是你所包含的擴展Array的模塊。 –

回答

0

看得很仔細,在你的第一個測試:

@fixtures.where(:name => 'The Wolf') 

@fixtures對象是Array類的,你在呼喚它的名字是where的方法。因此,要通過此測試,必須在Array或其父類之一上定義名爲where的方法。作爲第一次嘗試,你可以這樣寫:

class Array 
    def where(options) 
    end 
end 

我想這就是你要求的。在編寫上面的代碼之後,您應該從測試中獲得不同的錯誤消息。將代碼寫入where方法是爲了讓您的所有測試通過。

+0

謝謝@david grayson –