在不发送电子邮件的情况下测试模型回调
Testing model callback without firing email
我有一个 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
如果您只想检查是否调用了回调,那么我认为模拟 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
我有一个 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
如果您只想检查是否调用了回调,那么我认为模拟 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