Search code examples
ruby-on-railsfactory-botrspec-rails

Rails FactoryGirl trait association with model after_create callback not setting vanity_url


In my model, I have an after_create callback that triggers the method:

class Job < ActiveRecord::Base
  after_create :update_vanity_url

  private

  def update_vanity_url
    self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
  end
end

This sets up a custom url for my jobs, however, when I try to use this in my coupon factory it is not being saved. The coupon is created without a job assigned. Only when the coupon is used is it paired with one job. I referred to that as executed:

FactoryGirl.define do
  factory :coupon do
    code { rand(25**25) }
    percent_discount { rand(100**1) }
    start_at { Time.now }
    end_at { 30.day.from_now }

    trait :executed do |c|
      association :job, factory: [:job, :purchased] 
      c.executed_at { Time.now }
    end
  end
end

Ideally, I would like to be able to call FactoryGirl.create(:coupon, :executed) which works but the after_create is never called... Thoughts?

More details of this setup are covered here Rails FactoryGirl Factory with optional model association

Per issue comments below, I have added my routes section and updates:

Routes

  resources :jobs, only: [:new] do
    collection do
      post 'new', to: 'jobs#create'
    end
    get '/review', to: 'reviews#new'
    patch '/review', to: 'reviews#update'
    get '/payment', to: 'payments#new'
    patch '/payment', to: 'payments#update'
  end
  match '/jobs/:company_slug/:job_slug/:id', via: :get, to: 'jobs#show'

Solution

  • I researched this for hours, and this is what I found to work. It turns out it was not FactoryGirl, rather the model itself... I think...

      def update_vanity_url
        self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
        save
      end