Search code examples
ruby-on-railsrspeccallbackfactory-bot

Rails Rspec/Factory Bot isn't invoking model before_save callbacks


I have a user model with a number of before_save callbacks - for example, one that strips leading and trailing whitespace:

app/models/user.rb:

def strip_whitespace_in_user_names
  self.first_name.strip!
  self.first_name.gsub!(" ", "")
  self.last_name.strip!
  self.last_name.gsub!(" ", "")
end

I have a basic model spec, and I'd like to check that this actually works. For example, " Nathan " should return "Nathan"

spec/models/user_spec.rb:

RSpec.describe User, type: :model do
  let(:user) { build :poorly_defined_user }
  it "has no leading white space" do
    expect(user.first_name).not_to end_with(" ")
  end
end

Here is the factory definition of a poorly_defined_user:

require 'faker'
password = Faker::Internet.password
# Factory to define a user
FactoryBot.define do
  factory :poorly_defined_user, class: User do
    first_name "     asd  "
    last_name "AS DF  "
    handle "BLASDF824"
    email Faker::Internet.email
    password password
    password_confirmation password
  end
end

However, when I run the tests, this expectation fails. I checked on postman (this is for an API), and the callbacks are correctly run, and the user's attributes are properly set.

Any help as to why this is happening, or, how to restructure my tests to reflect how Rspec/Factory Bot actually work.


Solution

  • Change build to create like so:

    let(:user) { create :poorly_defined_user }

    When calling build, the object is not actually saved to the db so the callbacks don't fire.