Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rspec 如何为没有';还不存在_Rspec_Rspec Rails - Fatal编程技术网

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