chrishough chrishough - 6 months ago 30
Ruby Question

Rails 4 rspec 3 testing before validation

I am trying to build a spec to make sure duplicate companies are not created. When I used the following spec the company is properly assigned, however the factory still creates 3 companies. This is not the desired behavior.

How would I adjust this spec to meet the criteria for the before validation call back?

Spec

describe 'before validation' do
it 'prevents duplicate companies' do
company = create(:company)
job1 = create(:job, company: company)
job2 = create(:job, company: company)

binding.pry
end
end


Model

class Job < ActiveRecord::Base
...

before_validation :find_company

...

private

...

def find_company
existing_company = Company.where(email: company.email) if company
self.company = existing_company.first if existing_company.count > 0
end
end


Factory

FactoryGirl.define do
factory :job do
category
company
title { FFaker::Company.position }
location { "#{FFaker::Address.city}, #{FFaker::AddressUS.state}" }
language_list { [FFaker::Lorem.word] }
short_description { FFaker::Lorem.sentence }
description { FFaker::HTMLIpsum.body }
application_process { "Please email #{FFaker::Internet.email} about the position." }
end
end

Answer

Use the transient block to make this work...

FactoryGirl.define do
  factory :job do
    category
    transient do
      company
    end
    title { FFaker::Company.position }
    location { "#{FFaker::Address.city}, #{FFaker::AddressUS.state}" }
    language_list { [FFaker::Lorem.word] }
    short_description { FFaker::Lorem.sentence }
    description { FFaker::HTMLIpsum.body }
    application_process { "Please email #{FFaker::Internet.email} about the position." }
  end
end

Spec

  describe 'before validation' do
    it 'prevents duplicate companies' do
      company = create(:company)
      job1 = create(:job, company: company)
      job2 = create(:job, company: company)
      expect(Company.all.count).to eq(1)
    end
  end
Comments