Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.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
Ruby on rails 控制器规范:expect(Controller).to receive(:create)阻止执行#create操作_Ruby On Rails_Rspec_Controller_Mocking - Fatal编程技术网

Ruby on rails 控制器规范:expect(Controller).to receive(:create)阻止执行#create操作

Ruby on rails 控制器规范:expect(Controller).to receive(:create)阻止执行#create操作,ruby-on-rails,rspec,controller,mocking,Ruby On Rails,Rspec,Controller,Mocking,我有以下行动: def create binding.pry @finding.save respond_with @project, @finding end 运行以下测试时 it 'balances the consecutive numbers', focus: true do expect { post :create, params: {...} }.to change { Finding.count }.from(0).to 1 end …我首先显示b

我有以下行动:

def create
  binding.pry
  @finding.save
  respond_with @project, @finding
end
运行以下测试时

it 'balances the consecutive numbers', focus: true do
  expect {
    post :create, params: {...}
  }.to change { Finding.count }.from(0).to 1
end
…我首先显示
binding.pry
控制台(证明
#create
操作已实际执行),然后规范通过:

Finished in 4.24 seconds (files took 5.31 seconds to load)
1 example, 0 failures
现在,当我添加一个
expect(controller.),以接收(:create)

it 'balances the consecutive numbers', focus: true do
  expect(controller).to receive(:create) # This is new!

  expect {
    post :create, params: {...}}
  }.to change { Finding.count }.from(0).to 1
end
…然后再次运行测试,我立即显示此规范失败结果:

expected result to have changed from 0 to 1, but did not change
删除
更改{…}
期望值时

it 'balances the consecutive numbers', focus: true do
  expect(controller).to receive(:create)

  post :create, params: {project_id: @project.id, finding: {requirement_id: @requirement.id}}
end
…它再次通过:

1 example, 0 failures
但是,
#create
中的
binding.pry
仍然没有被调用

这是怎么回事?不知何故,
expect(controller)。接收(:create)
似乎阻止了实际的
#create
操作的执行!这不是我想要的。我希望它像往常一样执行

我在这里做错了什么?

当您使用
expect().to receive()
时,真正的方法被禁止了。。。它只是验证是否按预期调用了某些内容

我们通常在需要测试时使用它,如果我们不控制答案,或者我们想要模拟答案被调用

如果要检查是否调用了某些内容,并运行原始文件,则应使用:

expect(something).to receive(:some_method).and_call_original

我在AR回调中面临同样的问题。我得到了答案。谢谢