Sergey
Sergey

Reputation: 1001

how filled table in test database?

please help solve the problem.

model:

class StatusPoll < ActiveRecord::Base
  has_many :polls
end

class Poll < ActiveRecord::Base
  belongs_to  :status_poll
end

spec/factories/status_poll.rb:

FactoryGirl.define do
  factory :status_poll_0 do
    id 0
    title 'open'
  end

  factory :status_poll_1 do
    id 1
    title 'closed'
  end  
end

spec/factories/poll.rb:

FactoryGirl.define do
  factory :poll do
    association :status_poll_0
    sequence(:title){ |i| "title#{i}" }
    description Faker::Lorem.paragraph(7)
  end
end

i need fill table 'status_poll' follow values:

id: 0
title 'open'

id: 1
title: 'closed'

but after run specs in console i get follow error messages:

kalinin@kalinin ~/rails/phs $ rspec spec/models/poll_spec.rb
F...

Failures:

  1) Poll has a valid factory
     Failure/Error: expect(FactoryGirl.create(:poll)).to be_valid
     NameError:
       uninitialized constant StatusPoll0

Upvotes: 2

Views: 60

Answers (2)

Nathan
Nathan

Reputation: 7855

I wouldn't recommend the approach you're using.

Instead, create a general status_poll factory like so:

FactoryGirl.define do
  factory :status_poll do
  end
end

Then in your poll factory, create traits like so:

FactoryGirl.define do
  factory :poll do
    sequence(:title){ |i| "title#{i}" }
    description Faker::Lorem.paragraph(7)

    trait :poll_with_status_poll_0 do
      after :build, :create do |poll|
       status_poll = create :status_poll, id: 0, title: "open"
       poll.status_poll = status_poll
      end
    end

    trait :poll_with_status_poll_1 do
      after :build, :create do |poll|
       status_poll = create :status_poll, id: 1, title: "closed"
       poll.status_poll = status_poll
      end
    end
  end
end

Now in your specs, you can build the traits like so:

let(:poll_with_status_poll_0) { create :poll, :poll_with_status_poll_0 }
let(:poll_with_status_poll_1) { create :poll, :poll_with_status_poll_1 }

You really want to try to model your factories to mirror your rails models. In your approach, you're generating factory models that do not represent real classes in your app.

Upvotes: 1

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

uninitialized constant StatusPoll0

You are getting this error because you don't have any class named StatusPoll0. Rather you have a class named StatusPoll. So, you have to specify the class for your factories.

In your spec/factories/status_poll.rb, specify the class of the factory as following:

FactoryGirl.define do
  factory :status_poll_0, class: 'StatusPoll' do
    id 0
    title 'open'
  end

  factory :status_poll_1, class: 'StatusPoll' do
    id 1
    title 'closed'
  end  
end

This should fix your issue.

Upvotes: 1

Related Questions