Richlewis
Richlewis

Reputation: 15384

FactoryGirl Callbacks

I have the following associations and am trying to implement some factories that allow me to test fully with a has_many and has_many_through association

class Image < ActiveRecord::Base
  has_many :categories
end

class Category < ActiveRecord::Base
  belongs_to :image
  has_many :image_categories
  has_many :images, through: :image_categories
end

class ImageCategory < ActiveRecord::Base
  # Holds image_id and category_id to allow multiple categories to be saved per image, as opposed to storing an array of objects in one DB column
  belongs_to :image
  belongs_to :category
end

So with ImageCategory I am under the impression that when i save an Image object the image_id and category_id will save in the ImageCategory Table? I have yet to see this mind in my application

So when creating a factory this is what i have so far

FactoryGirl.define do
  factory :image do
    title 'Test Title'
    description 'Test Description'
    photo File.new("#{Rails.root}/spec/fixtures/louvre_under_2mb.jpg")

  factory :image_with_category, parent: :image do
    categories { build_list :category, 1 }
  end

  factory :image_no_title do
    title nil
  end

 factory :image_no_description do
   description nil
 end

 factory :image_no_category, parent: :image do 
   categories { build_list :category, 0 }
 end
end
 end 

I don't understand what the integer value is after the category in build_list? is it the number of instances ?

This test will pass

it 'is valid with an associated Category' do
  expect(FactoryGirl.build(:image_with_category)).to be_valid
end

yet this one will fail

it 'is invalid with no category' do
  @image = FactoryGirl.build(:image_no_category)
  @image.save
  expect(@image.errors[:category]).to eq(["Don't forget to add a Category"])
end

expected: ["Don't forget to add a Category"]
got: []

What have i done wrong here?

Thanks

Upvotes: 1

Views: 157

Answers (1)

Alexander Shlenchack
Alexander Shlenchack

Reputation: 3869

You are correct the build_list is the FactoryGirl helper for building instances. And in your second test you don't have any errors because you don't have any validation at all.

Upvotes: 1

Related Questions