首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在不触发电子邮件的情况下测试模型回调

在不触发电子邮件的情况下测试模型回调
EN

Stack Overflow用户
提问于 2019-07-02 20:34:50
回答 1查看 37关注 0票数 0

我有一个Rails 5应用程序,正在我的模型中测试回调。我希望确保回调被调用,但我不想实际触发以下行,因为它调用API并发送电子邮件:

代码语言:javascript
复制
response = bird.request(body, employee.location.birdeye)

我的测试如下:

代码语言:javascript
复制
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()的调用的情况下测试此回调?这是我的模型:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-07 15:56:00

如果您只想检查回调是否被调用,那么我认为模拟send_request可能是可行的。请尝试以下操作

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56852627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档