【发布时间】:2020-02-01 19:27:30
【问题描述】:
我有一个实现.call 方法的类,该方法为块生成一个对象,我想学习如何为此编写单元测试。这就是我所拥有的。
module A
class B < Service
def call(object_id:)
@object = Something.find(object_id)
@object.update(status: 'done')
yield @object
end
def set_to_in_progress
@object.update(status: 'in_progress')
end
end
end
class Service
def self.call(*args); new.call(*args); end
end
然后我这样使用它:
A::B.call(obj) do |object|
object.set_to_in_progress if some_other_condition?
end
我需要能够为call 方法编写单元测试,以测试状态是否已更改为完成或进行中。这是我所拥有的:
RSpec.describe A::B, :unit do
let(:object) { create(:something, id: 1, status: 'in_progress') }
it 'updates the status to done' do
described_class.call(object.id) do |???|
???
end
expect(object.status).to equal('done')
end
it 'updates the status to in progress' do
described_class.call(object.id) do |???|
???
end
expect(object.status).to equal('in_progress')
end
end
【问题讨论】:
-
这个规范会不会失败,因为
Something.find(object_id)将找不到记录,因为您从未在规范中创建记录? -
@Kris 你说得对,好地方!我已经修好了。
标签: ruby rspec rspec-rails rspec3