我有一个Rails 5应用程序,正在我的模型中测试回调。我希望确保回调被调用,但我不想实际触发以下行,因为它调用API并发送电子邮件:
response = bird.request(body, employee.location.birdeye)我的测试如下:
it 'expects to send request through birdeye if valid' do
req = build(:review_request)
expect(req).to receive(:send_request)
req.save
end这行得通,但是上面提到的这行被触发了。如何在不触发对bird.request()的调用的情况下测试此回调?这是我的模型:
class ReviewRequest < ApplicationRecord
belongs_to :user
belongs_to :review, optional: true
belongs_to :employee, optional: true
after_create :send_request
def client
self.user.client
end
def send_request
p "send_request callback..."
ap self
ap client
body = {
name: client.try(:name),
emailId: user.email,
phone: client.try(:phone),
employees: [
{
emailId: employee.try(:email)
}
]
}
bird = Birdeye.new
response = bird.request(body, employee.location.birdeye)
ap body
return response
end
end发布于 2019-07-07 15:56:00
如果您只想检查回调是否被调用,那么我认为模拟send_request可能是可行的。请尝试以下操作
before do
allow_any_instance_of(ReviewRequest).to receive(:send_request).and_return(true)
end
it 'expects to call :send request after creating a ReviewRequest' do
allow_any_instance_of(ReviewRequest).to receive(:send_request)
create(:review_request)
end如果您想测试send_request的实现,那么可以使用存根Birdeye
https://stackoverflow.com/questions/56852627
复制相似问题