在ruby类上模拟initialize方法?

在ruby类上模拟initialize方法?,ruby,mocking,Ruby,Mocking,如何在ruby类上模拟initialize方法 我正在做一些测试,希望模拟从新调用创建的对象 我试着写了一些东西,但没有一个能让mock类从新调用中返回。它只是不断返回正常的、预期的对象 编辑: 一次尝试- class MockReminderTimingInfoParser < ReminderTimingInfoParser def new(blank) ReminderTimingInfoParserForTest.new end end describe Remi

如何在ruby类上模拟initialize方法

我正在做一些测试,希望模拟从新调用创建的对象

我试着写了一些东西,但没有一个能让mock类从新调用中返回。它只是不断返回正常的、预期的对象

编辑:

一次尝试-

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
class MockReminderingInfoParser
您能否继承该类,然后提供自己的初始化

class MockReminderTimingInfoParser < ReminderTimingInfoParser
  def new(blank)
    ReminderTimingInfoParserForTest.new
  end
end
另一个方法是打开
MockRemingInfoParser
的singleton类:

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

我很困惑。是否要模拟
初始化
新建
?是否初始化提供新功能的方法?这是一个我不太了解的ruby细节。你说的“它给了你
新的
”是什么意思?给你
new
的方法是
new
,就像给你
foobar
的方法是
foobar
;结束,我定义初始化;结束。我以为这是Ruby中的某种特殊情况。我试过了,但似乎不起作用。我将在问题的编辑中发布我的代码。无论哪种方式都不起作用。如果你有一段代码的例子,我很想看看。谢谢!我刚刚通过一些博客文章了解到了这一点,但你的回答非常好,再次感谢。您的一些代码为我提供了更简洁的方法来完成我的工作。我特别喜欢以下语法:def rementingInfoParser.new(*args)rementingInfoParserfortest.new end
class MockReminderTimingInfoParser < ReminderTimingInfoParser
  def self.new(blank)
    ReminderTimingInfoParserForTest.new
  end
end