如何为尚不存在的对象设置RSpec期望

时间:2014-12-18 00:32:21

标签: rspec rspec-rails

如何在创建记录时测试邮件是否发送到MyCoolClass

describe MyModel, type: :model do
  it 'should call this class' do
    # how do I set the expectation of new_record_id?
    expect_any_instance_of(MyCoolClass).to receive(:a_method).with(new_record_id, :created)
    MyModel.create
  end
end

唯一的选择是:

describe MyModel, type: :model do
  it 'should call this class' do
    new_record = MyModel.new
    expect_any_instance_of(MyCoolClass).to receive(:a_method).with(new_record, :created)
    new_record.save
  end
end

这里的问题是,我正在测试save,而不是create,这对我的情况大多是好的。但更大的问题是,这意味着我必须更改MyCoolClass的实现以传递记录,而不是id

1 个答案:

答案 0 :(得分:2)

我看到两个变种

1)使用anythingkind_of(Numeric)

it 'should call this class' do
  expect_any_instance_of(MyCoolClass).to receive(:a_method).with(kind_of(Numeric), :created)
  MyModel.create
end

2)存根savecreate方法并返回double

let(:my_model) { double(id: 123, save: true, ...) }

it 'should call this class' do
  MyModel.stub(:new).and_return(my_model)
  expect_any_instance_of(MyCoolClass).to receive(:a_method).with(my_model.id, :created)
  MyModel.create
end