Rspe c тестирование обратных вызовов жизненного цикла в Rails? - PullRequest
0 голосов
/ 08 апреля 2020

Я хотел бы реализовать более подробное тестирование RSpe c для методов модели Rails, в частности, обратного вызова жизненного цикла. Как мне написать тест для такого метода:


class Service < ApplicationRecord
    has_many :outages 
    has_many :notes


   before_save :create_or_update_outage

   private 


  def create_or_update_outage
    if is_down
      Outage.create!(service: self, start_time: Time.now)
    else
      Outage.where(service: self, end_time: nil).last.update(end_time: Time.now)

    end
  end
end

Мой файл rspe c выглядит так:

RSpec.describe Service, type: :model do
  let(:service) { build(:service) }

  describe "Validation" do
    it { should allow_value(service.name).for(:name) }
    it { should allow_value(service.is_down).for(:is_down)}
  end 

  describe "Associations" do 
    it { should have_many(:outages) }
  end

  context 'Test Custom Methods' do 
    # Implement testing here
  end


end

Я использую FactoryBot и Shoulda Спички за помощь.

Обновление

Вот модель отключения:

class Outage < ApplicationRecord
    belongs_to :service

    # after_save :create_note 
    # after_update :update_note, if: !self.service.is_down

    private 

    # Creates an automated note from user 1 (automation) on service down and outage create.
    # If service goes back up, the outage remains and another automated note is created
    def create_note 
        self.notes.create(user_id: 1, outage: self, entry: "Outage started at #{Time.now} for #{Service.where(id: self.service_id).name}")
    end 

    def update_note 
        self.notes.update(user_id: 1, outage: self, entry: "Outage ended at #{Time.now} for #{Service.where(id: self.service_id).name}")
    end 

end

Заводская модель:

FactoryBot.define do
  factory :outage do
    start_time { Time.now }
    end_time { nil }
    is_recurring { false }
    reason { nil }
  end
end

и

FactoryBot.define do
  factory :service do
    name { ["AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL"].sample }
    is_down { [false, true].sample }
  end
end
...