【发布时间】:2021-08-27 21:12:59
【问题描述】:
试图在 RSpec 单元测试中模拟 ActiveRecord 模型类。在这里我总结一下。
RSpec 测试
it 'calls create method' do
response_code = post @url, params: { id: @id }
expect(response_code).to eql(200)
allow(MyModel).to receive(:create)
expect(MyModel).to receive(:create)
end
控制器方法
控制器入口点。
def controller_method
other_model_method
#...
render json: #...
end
调用 MyModel 的其他模型
Class OtherModel < ActiveRecord
#...
def other_model_method
MyModel.create(attr: value)
end
end
运行我得到的测试:
(MyModel(id: integer).create(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
我是 Rails 和 Ruby 的新手。这对 allow(MyModel)/expect(MyModel) 我在另一篇文章中看到但不适合我。我做错了什么?
【问题讨论】:
-
从问题中不清楚您实际上要完成什么或实际上应该测试什么行为。 “调用创建方法”不是一种行为 - 它是实现。
allow(MyModel).to receive(:create)将用模拟替换原始方法。expect(MyModel).to receive(:create)也存根该方法,但它也设定了该方法应该/已经被调用的期望。 relishapp.com/rspec/rspec-mocks/v/3-10/docs/basics
标签: ruby-on-rails ruby rspec mocking