2010-09-15 102 views
2

如何模擬ruby類的初始化方法?模擬ruby類的初始化方法?

我正在做一些測試,並想嘲笑從新調用創建的對象。

我試着寫了幾件事情,他們都沒有看到從新調用返回的模擬類。它只是不斷返回正常的,預期的對象。

編輯:

一個嘗試 -

class MockReminderTimingInfoParser < ReminderTimingInfoParser 
    def new(blank) 
    ReminderTimingInfoParserForTest.new 
    end 
end 

describe ReminderParser do 
    parser = ReminderParser.new(MockReminderTimingInfoParser) 

    it "should parse line into a Reminder" do 
    parser.parse(" doesnt matter \"message\"").should == Reminder.new('message', ReminderTimingInfo.new([DaysOfWeek.new([:sundays])], [1])) 
    end 
end 

class ReminderTimingInfoParserForTest 
    include TimingInfoParser 

    def parse_section(section); [DaysOfWeek.new([:sundays]), 1] end 

    def reminder_times_converter(times); times end 
end 
+0

我很困惑。你想模擬'initialize'還是'new'? – 2010-09-15 23:25:04

+0

是不是初始化給你新的方法?這是一個我不太瞭解的紅寶石細節。 – 2010-09-15 23:32:43

+0

你是什麼意思「給你新''」?給你'new'的方法是'new',就像給你foobar的方法是'foobar'一樣。 – 2010-09-15 23:43:27

回答

2
class MockReminderTimingInfoParser < ReminderTimingInfoParser 
    def new(blank) 
    ReminderTimingInfoParserForTest.new 
    end 
end 

在這裏,你要定義爲類MockReminderTimingInfoParser的所有實例叫new方法。在你的問題中,你提到你想要掛鉤實例創建。但是,在Ruby中,實例創建不是由實例方法完成的。顯然,這是行不通的,因爲爲了調用一個實例方法,你需要先創建一個實例!

而是通過調用類上的工廠方法(通常稱爲new)來創建實例。

換句話說,爲了創建一個MockReminderTimingInfoParser的實例,您可以調用MockReminderTimingInfoParser.new,但是您已經定義了一個方法MockReminderTimingInfoParser#new。爲了調用您定義的方法,您必須致電MockReminderTimingInfoParser.new.new

您需要在MockReminderTimingInfoParser的單例類中定義一個方法。有幾種方法可以做到這一點。一種方式是僅僅模仿的方式將通話方法:

def MockReminderTimingInfoParser.new(blank) 
    ReminderTimingInfoParserForTest.new 
end 

另一個辦法是開放MockReminderTimingInfoParser的單例類:

class << MockReminderTimingInfoParser 
    def new(blank) 
    ReminderTimingInfoParserForTest.new 
    end 
end 

然而,在這兩種情況下,MockReminderTimingInfoParser顯然必須先存在。鑑於你需要定義類,這裏是定義類(或模塊)單例類的最習慣方法:

class MockReminderTimingInfoParser < ReminderTimingInfoParser 
    def self.new(blank) 
    ReminderTimingInfoParserForTest.new 
    end 
end 
+0

這兩種方式似乎都沒有工作。如果你有一個可用的代碼片段,我很樂意看到它。 – 2010-09-15 23:43:18

+0

謝謝!我只是通過一些博客文章瞭解到這一點,但您的答案非常好,再次感謝。你的一些代碼爲我提供了更乾淨的方式來完成我的工作。 – 2010-09-16 00:24:43

+0

我尤其喜歡這種語法: – 2010-09-16 00:27:18

0

你能繼承的類,然後提供自己的初始化?

+0

我試過了,它似乎不起作用。我將在編輯中發佈我的代碼以解決問題。 – 2010-09-15 23:32:11