测试该方法是用rspec在另一个方法中调用的

时间:2018-04-25 12:40:33

标签: ruby-on-rails ruby testing rspec rspec-rails

我必须为以下方法编写规范:

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'。我做错了什么?

2 个答案:

答案 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

我建议使用方法调用来验证参数。