Rspec 如何为没有';还不存在
在创建记录时,我如何测试消息是否发送到Rspec 如何为没有';还不存在,rspec,rspec-rails,Rspec,Rspec Rails,在创建记录时,我如何测试消息是否发送到mycolclass 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) MyMo
mycolclass
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
,这对我的情况基本上是可以的。但更大的问题是,这意味着我必须更改mycolclass
的实现以传递记录,而不是id
我看到了两个变体
1) 使用或
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
非常聪明。这两个我都没想到。谢谢
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