Question

I'm trying to run some tests on a model "Click".

# models/click_spec.rb
describe Click do
    it "should have a valid constructor" do
        FactoryGirl.create(:click).should be_valid
    end
end

The objective is that the model uses two tables that have the same country. I don't want to use a sequence for the country (as I found for Emails). But it raise this error:

Validation failed: Name has already been taken, Slug has already been taken

The problem is that it seems that it create twice the country [name:"United States", slug:"us"]

Here's the factories used.

# factories/countries.rb
FactoryGirl.define do
    factory :country do
        name "United States"
        slug "us"
    end
end

# factories/offers.rb
FactoryGirl.define do
    factory :offer do
        association :country, factory: :country
        # Other columns
    end
end

# factories/users.rb
FactoryGirl.define do
    factory :user do
        association :country, factory: :country
        # Other columns
    end
end

# factories/clicks.rb
FactoryGirl.define do
    factory :click do
        association :offer, factory: :offer
        association :user, factory: :user
        # Other columns
    end
end

and the model of Country:

class Country < ActiveRecord::Base
    validates :name, :slug,
    presence: true,
    uniqueness: { case_sensitive: false }

    validates :slug,
    length: { is: 2 }

end

I've tried to change the association strategy to something like this:

association :country, factory: :country, strategy: :build

But it raise this error:

Validation failed: Country can't be blank

Any idea?

Thanks,

Was it helpful?

Solution

As per the shared code,

when you call FactoryGirl.create(:click),

it will go to execute factory :click where it finds association :offer, factory: :offer which in turn calls factory: :offer where you create a country with name "United States" and slug "us" for the first time.

Again, in factory :click, it finds association :user, factory: :user which in turn calls factory: :user where you create a country again with the same name "United States" and slug "us" for the second time.

Issue #1: Validation failed: Name has already been taken, Slug has already been taken

The above error is because of the uniqueness constraint on Country model for name and slug.

Issue #2: Validation failed: Country can't be blank

When you do association :country, factory: :country, strategy: :build then strategy: :build only creates an instance of Country, it does create a record in database.

The Country can't be blank error is because you didn't create a country record in the database for user and offer. And you must be having a validation presence: true in these two models for country OR schema level check of not null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top