ruby-on-railsrspecrspec-railsshouldarspec-expectations

How to test before_validation callback model concerns in rspec


I'm learning to write specs for my code and I'm still new to it. Trying to write specs / SharedExamples for my Model concerns, but I don't understand how to write it as I find this one very complicated.

If someone could help me or show me how to write spec for codes like these would be very helpful. Below is my concern AddStakeholder.

module AddStakeholder
  extend ActiveSupport::Concern

  included do
    before_validation -> { add_stakeholders }
  end

  private

  def add_stakeholders
    return unless self.stakeholder

    company = if self.is_a?(Certificate)
                self.round ? self.round.company : self.company
              else
                self.company
              end
    existing_stakeholder = company.stakeholders.find_by_email(self.stakeholder.email)
    if existing_stakeholder.present?
      if self.stakeholder.name == existing_stakeholder.name
        self.stakeholder = existing_stakeholder
      else
        self.stakeholder.company = company
      end
    else
      self.stakeholder.company = company
    end
  end
end

Solution

  • There's not enough information in your code snippet to prepare a full example but it would look somewhat along the lines of:

    RSpec.describe Thing, type: :model do
      it "adds stakeholders" do
        t = Thing.new(...)
        expect(t).to be_valid # or .to_not be_valid depending on your validations on Thing
        expect(t.stakeholder).to ... # whatever you expect it to be
      end
    end