【问题标题】:Testing ActiveRecord:Observer using RSpec使用 RSpec 测试 ActiveRecord:Observer
【发布时间】:2014-08-16 02:16:07
【问题描述】:

我有一个模型类如下:

class DataInfo < ActiveRecord::Base
  STATUS = {:UNAPPROVED => 1, :APPROVED => 2, :PROCESSED => 3 }
  attr_accessible :id, :owner, :status
  validates :status, :inclusion => {:in => STATUS.values}    
end

我写了一个观察者如下:

class StatusObserver < ActiveRecord::Observer
  def after_save(datainfo)
    if datainfo.status.eql? "APPROVED"
      DataInfoWorker.perform_async datainfo.id
    end 
  end
end

如何使用 RSpec 测试观察者?我一定要使用“No Peeping Toms”插件吗?我主要是想测试 after_save 的一部分吗?

【问题讨论】:

    标签: ruby-on-rails activerecord rspec observer-pattern


    【解决方案1】:

    你应该能够使用 rspec-3 语法做这样的事情:

    describe DataInfo do
      describe 'after save when status is APPROVED' do
        let(:data_info) { DataInfo.new(status: :APPROVED) }
    
        before do
          data_info.save!
        end
    
        it 'queues DataInfoWorker' do
          expect(DataInfoWorker.jobs.size).to eq 1
        end
    
      end
    end
    

    已更新以测试 Sidekiq 作业是否已排队。确保将rspec-sidekiq gem 添加到您的Gemfile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-28
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多