ruby-on-rails - 接收(:创建)的 Controller 规范 : expect(controller). 阻止执行#create 操作

标签 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

...我首先显示了 binding.pry 控制台(证明 #create 操作实际上已执行),然后规范通过:

Finished in 4.24 seconds (files took 5.31 seconds to load)
1 example, 0 failures

现在当我添加一个 expect(controller).to receive(: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

当删除 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).to receive(:create) 似乎阻止了实际的 #create 操作被执行!这不是我想要的。我希望它像往常一样执行。

我在这里做错了什么?

最佳答案

当您使用 expect().to receive() 时,真正的方法被抑制了……它只是验证是否按预期调用了某些东西……

当我们想要测试我们是否无法控制答案或者我们想要模拟答案被调用时,我们通常会使用它。

如果你想检查是否调用了某些东西,并运行原始的,你应该使用:

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

https://relishapp.com/rspec/rspec-mocks/v/3-5/docs/configuring-responses/calling-the-original-implementation

关于ruby-on-rails - 接收(:创建)的 Controller 规范 : expect(controller). 阻止执行#create 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420582/

相关文章:

rspec 的 should_receive 在非模拟对象上?

ruby-on-rails - 未定义的FactoryGirl transient 变量方法

asp.net-mvc - ViewModel 内的 MVC3 RouteUrl

ruby-on-rails - 存储应用程序参数 : database, 文件、代码...的最佳位置在哪里?

ruby-on-rails - 如何从Rails ActiveRecord获取昨天的数据

ruby-on-rails - Friendly_id 和 rspec Controller 测试,找到正确的 id

.net - 如何本地化 ASP.NET MVC 应用程序中的 Controller 名称和操作?

java - 注入(inject)到 Spring Controller 中的服务在其中一个功能中不可用

ruby-on-rails - Rails 3.2中clone方法的问题

ruby-on-rails - Capybara-webkit 抛出找不到变量 : $