我想测试遍历哈希数组的简单类,并仅返回状态为Pending且已更新超过2天的那些。
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
如何测试fields
方法,这是Jira-Ruby gem的方法。我认为它是comes from here (Field class in resource of gem),因为我在其他任何地方都找不到fields
方法。
调试后我的想法是:
project.class
-数组
[issue.class
-JIRA :: Resource :: Issue
我自然的想法是:
before do
# (...) some other mocks
allow(JIRA::Resource::Issue).to receive(:fields)
end
但是我遇到错误:
失败/错误:allow(JIRA :: Resource :: Issue).to接收(:fields)
JIRA :: Resource :: Issue未实现:字段
我在DAYS一直在为这个问题而苦苦挣扎,我在这里非常拼命。如何模拟此方法?
这是我其余的规格:
RSpec.describe FetchPending do
subject { described_class.new }
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(described_class::PROJECT_KEY).and_return(project)
allow(project).to receive(:call).and_return(project_hash)
allow(JIRA::Resource::Issue).to receive(:fields)
end
it 'return project hash' do
expect(subject.call).include(key[:'TP-47'])
end
这不是模拟它以返回项目的正确语法; and_return
用于返回value(例如字符串或整数),而不是对象。对于对象,必须将其作为块发送。此外,如果call
是返回[project_hash]值的Jira::ProjectConnection
对象上的有效方法,则可以在声明实例double时直接模拟其行为(Relish文档尚不清楚此功能还不错)。这样的事情可能会起作用:
let(:project) { instance_double(Jira::ProjectConnection, call: project_hash) }
before do
# Ensure new proj conns always return mocked 'project' obj
allow(Jira::ProjectConnection).to receive(:new).with(
described_class::PROJECT_KEY
) { project }
allow(JIRA::Resource::Issue).to receive(:fields) # not sure if necessary?
end