Ruby RSpec-如何测试对象是否在#初始化中向self发送消息

Ruby RSpec-如何测试对象是否在#初始化中向self发送消息,ruby,rspec,Ruby,Rspec,读完这个问题后,我真的不喜欢这个答案 也许我有第三种情况。这就是我现在所拥有的,灵感来自于答案中的第二个代码 # Picture is collection of SinglePictures with same name and filename, # but different dimensions class Picture attr_accessor :name, :filename attr_reader :single_pics, :largest_width def

读完这个问题后,我真的不喜欢这个答案

也许我有第三种情况。这就是我现在所拥有的,灵感来自于答案中的第二个代码

# Picture is collection of SinglePictures with same name and filename,
# but different dimensions
class Picture
  attr_accessor :name, :filename
  attr_reader :single_pics, :largest_width

  def initialize(name, filename, dimensions=nil)
    @largest_width = 0
    @single_pics = {}
    add_single_pics(dimensions) if dimensions
  end

  def add_single_pics(max_dimension)
    # logic
  end
end

describe '#initialize' do
  it 'should not call add_single_pics if dimensions is not given' do
    subject = Picture.new('Test Picture', 'Test-Picture')
    expect(subject.largest_width).to eq 0
  end

  it 'should call add_single_pics if dimensions are given' do
    subject = Picture.new('Test Picture', 'Test-Picture', 1920)
    expect(subject.largest_width).to eq 1920
  end
end
我真的不喜欢这样,因为我正在测试初始化测试中添加单个图片的功能。我想以某种方式在规范中写下:

  expect(subject).not_to have_received(:add_single_pics)
  expect(subject).to have_received(:add_single_pics)
但我明白了

Expected to have received add_single_pics, but that object is not a spy
or method has not been stubbed.
我能解决这个问题吗

间谍是支持这种模式的另一种双重测试类型 通过允许您期望在 事实上,你已经收到了

只有spy对象可以存储方法调用。要以您想要的方式测试真正的类,必须在初始化类之前使用
expect\u任何
语句的实例:

expect_any_instance_of(Picture).to receive(:add_single_pics)
Picture.new('Test Picture', 'Test-Picture')
在这种情况下,将调用
add_single_pics
方法,但其逻辑将不会运行,如果需要运行,则需要在匹配器上调用
和\u call_original
方法:

expect_any_instance_of(Picture).to receive(:add_single_pics).and_call_original

糟糕的是,他们说这是为了遗留代码,而想要使用它是一种代码味道。我写的代码很臭吗?哈哈。我想在使用
Picture
类时保存一行代码,而不必在新建后调用add\u single\u pics。