小编Lui*_*que的帖子

如何使用Rspec和FactoryGirl测试rails模型中的before_update回调?

我试图测试下面的模型的before_update回调.

车型/ option.rb:

class Option < ApplicationRecord
  belongs_to :activity

  has_many :suboptions, class_name: "Option", foreign_key: "option_id"

  belongs_to :parent, class_name: "Option", optional: true, foreign_key: "option_id"

  accepts_nested_attributes_for :suboptions, allow_destroy: true,
    reject_if: ->(attrs) { attrs['name'].blank? }

  validates :name, presence: true

  before_create :set_defaults
  before_update :set_updates


  def set_defaults
    self.suboptions.each do |sbp|
      sbp.activity_id = self.activity_id
    end
  end

  def set_updates
    suboptions.each do |child|
      child.activity_id = self.activity_id
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

规格/型号/ option.rb:

require 'rails_helper'

RSpec.describe Option, type: :model do

  describe "Callbacks" do
    it "before_create" do
      suboption = create(:option)
      option …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails callback beforeupdate factory-bot

2
推荐指数
2
解决办法
2024
查看次数