2010-09-15 101 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