如何在创建记录时测试邮件是否发送到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
。
答案 0 :(得分:2)
我看到两个变种
it 'should call this class' do
expect_any_instance_of(MyCoolClass).to receive(:a_method).with(kind_of(Numeric), :created)
MyModel.create
end
2)存根save
或create
方法并返回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