【问题标题】:Testing a Rails JSON API resource callback测试 Rails JSON API 资源回调
【发布时间】:2018-07-02 10:04:24
【问题描述】:

如何单元测试我的 JSON API 资源回调已注册为 after_create,并且调用了 send_notifications,我可以 expect(MyMailer).to receive(:welcome_email)

当我尝试allow & expect MyResource#send_notifications 或 MyMailer.welcome_email 时,他们的呼叫不会被跟踪。

    class MyResource < BaseResource

      after_create :send_notifications

      def send_notifications
        MyMailer.welcome_email(_model).deliver
      end
    end


    # rspec

    RSpec.describe Creem::Jpi::V1::MyResourceResource, type: :resource do
      include JsonApiResourceHelpers

      let(:my_resource) { create(:my_resource) }
      subject { described_class.new(my_resource, {}) }

      it { expect(described_class).to be < BaseResource }

      describe 'callbacks' do
        xit 'how do I unit test my callbacks?'
      end
    end

【问题讨论】:

    标签: ruby-on-rails jsonapi-resources


    【解决方案1】:

    我通过对邮件程序进行功能测试解决了这个问题。

    这可以通过在控制器规范中添加一个测试用例来完成,该测试用例用于触发资源回调的控制器操作。

        RSpec.describe MyResourceController, type: :controller do
          describe 'POST #create' do
            subject { post :create, params: { data: data } }
    
            it 'sends new notifications' do
              expect { subject }.to change { ActionMailer::Base.deliveries.size }.by(1)
            end
          end
        end
    

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 2015-12-19
      • 2012-05-30
      相关资源
      最近更新 更多