我想测试遍历哈希数组的简单类,并仅返回状态为Pending
且已更新两天以上的类。
fetch_pending.rb
class FetchPending
PROJECT_KEY = 'TPFJT'
TWO_DAYS = Time.now - 2 * 24 * 60 * 60
def call
project.select do |issue|
issue.fields.dig('status', 'name') == 'Pending' &&
DateTime.parse(issue.fields.dig('updated')) < TWO_DAYS
end
end
private
def project
@project ||= Jira::ProjectConnection.new(PROJECT_KEY).call
end
end
specs
RSpec.describe FetchPending do
subject { described_class.new }
let(:project_key) { 'TSW-123' }
let(:project_hash) do
[
{
'key': 'TP-47',
'fields': {
'status': {
'name': 'Pending'
},
'assignee': {
'name': 'michael.kelso',
'emailAddress': '[email protected]'
},
'updated': '2020-02-19T13:20:50.539+0100'
}
}
]
end
let(:project) { instance_double(Jira::ProjectConnection) }
before do
allow(Jira::ProjectConnection).to receive(:new).with('TSW-123').and_return(project)
allow(project).to receive(:call).and_return(project_hash)
end
it 'return project hash' do
expect(subject.call).include(key[:'TP-47'])
end
但是我有一个错误:
Failure/Error: expect(subject.call).include(key[:'TP-47'])
#<Jira::ProjectConnection (class)> received :new with unexpected arguments
expected: ("TSW-123")
got: ("TPFJT")
Please stub a default value first if message might be received with other args as well.
我在其他一些规范中也遇到了同样的问题,如何对这个变量进行存根处理?我应该用TWO_DAYS
吗?
[实际代码正在将FetchPending::ProjectKey
作为参数传递给Jira::ProjectConnection.new
。
在测试中,您正在定义一个变量:
let(:project_key) { 'TSW-123' }
但是实际上并没有在任何地方使用。
一个简单的解决方法就是更改
allow(Jira::ProjectConnection).to receive(:new).with('TSW-123').and_return(project)
with
allow(Jira::ProjectConnection).to receive(:new).with(described_class::PROJECT_KEY).and_return(project)