blakeage
blakeage

Reputation: 268

Inclusion in validation and Rspec using FactoryGirl

I'm having troubles testing an ActiveRecord inclusion validation in Rails with Factory Girl and Rspec. The inclusion validation always fails. Here is my code:

class FruitType
  has_many :fruits
end

class Fruit
  belongs_to :fruit_type
  validates :fruit_type_id, numericality: { only_integer: true }
  validates :fruit_type_id, inclusion: { in: FruitType.pluck(:id), message: "is invalid" }
end

FactoryGirl.define do
  factory :fruit_type_apple, class: FruitType do
     name "Apple"
  end
end

FactoryGirl.define do 
  factory :valid_fruit, class: Fruit do
    name "Red Apple"
    association :fruit_type, factory: :fruit_type_apple
  end
end

Rspec test is:

it "should have valid factory" do
  f = FactoryGirl.build( :valid_fruit )
  puts f.fruit_type_id
  puts "\n#{FruitType.all.pluck(:id)}"
  expect(f).to be_valid
end

Result is:

1

[1] F..........

Failures:

1) Fruit when validated should have valid factory Failure/Error: expect(f).to be_valid expected # to be valid, but got errors: Fruit type is invalid

As you can see, I've printed out the Fruit Type id list in the test, which includes only 1. And I've printed out the value of fruit_type_id for the fruit, which is 1. Yet, the inclusion validation still fails.

If I do the same thing in the rails console just by creating fruits and types manually, the validation works fine, it's just when I run the test I'm seeing this behavior. Any ideas? I must be missing something about Factory Girl here.

Upvotes: 2

Views: 720

Answers (1)

Mike Szyndel
Mike Szyndel

Reputation: 10592

You shouldn't validate the fruit_type_id attribute, rather use presence validation

validates :fruit_type, presence: true

Upvotes: 2

Related Questions