我必须为以下方法编写规范:
def track_event
tracker = set_tracker
category = define_event_category
tracker.event(category: category, action: name, label: properties['short_name'], value: properties['paid'])
end
具体来说,我必须检查调用event
时是否在变量tracker
上调用方法track_event
。我试着这样做:
describe '#track_event' do
it 'should call event method' do
expect(tracker).to receive(:event)
end
end
并收到错误undefined local variable or method 'tracker'
。我做错了什么?
答案 0 :(得分:1)
您无法访问tracker
,因为它是一个本地变量。
您可以改为隐藏set_tracker
方法并返回instance double:
describe '#track_event' do
let(:tracker_double) { instance_double(Tracker) }
it 'should call event method' do
allow(foo).to receive(:set_tracker).and_return(tracker_double)
expect(tracker_double).to receive(:event)
foo.track_event
end
end
foo
是您的考试科目。
答案 1 :(得分:0)
假设在你的rspecs中,subject
是定义track_event
方法的类的实例,你可以将从set_tracker
返回的值存根到你定义的对象,然后检查是否在event
对象上调用方法tracker
。
describe '#track_event' do
# Build a tracker object
let(:tracker) { <Whatever type of object you expect as a tracker> }
# Stub the output of `set_tracker`
before { allow(subject).to receive(:set_tracker) { tracker } }
it 'should call event method' do
expect(tracker).to receive(:event)
end
after { subject.track_event }
end
我建议使用方法调用来验证参数。