stackov8
stackov8

Reputation: 434

how make object with assotiation in rspec?

please help solve the problem. i need make object 'user' via gem factory_girl.

db schema:

create_table "statuses", force: :cascade do |t|
  t.string "title"
end

create_table "users", force: :cascade do |t|
  t.string   "email",                  default: "", null: false
  t.string   "encrypted_password",     default: "", null: false
  t.integer  "status_id",              default: 0
  t.string   "name"
end

factories/users.rb:

FactoryGirl.define do
  factory :user do
    sequence(:name){ |i| "us#{i}" }
    sequence(:email){ |i| "us#{i}@ad.ad" }
    password 'qwerty'
    password_confirmation{ |u| u.password } 
    status_id FactoryGirl.create(:status0)  
  end
end

factories/statuses.rb:

FactoryGirl.define do
  factory :status0 do
    id 0
    title 'user'
  end

  factory :status1 do
    id 1
    title 'manager'
  end

  factory :status2 do
    id 2
    title 'admin'
  end    
end

spec/controllers/users_controller_spec.rb:

describe UsersController, type: :controller do
  describe 'users:index action' do
    it 'check response status code for index page' do
      user = FactoryGirl.create(:user)  
      visit users_path
      expect(response).to be_success 
    end 
  end 
end 

but after run tests console display follow error message:

kalinin@kalinin ~/rails/phs $ rspec spec/controllers/users_controllers_spec.rb:104
/home/kalinin/.rvm/gems/ruby-2.0.0-p598/gems/activesupport-4.2.1/lib/active_support/inflector/methods.rb:261:in `const_get': uninitialized constant Status0 (NameError)
  from /home/kalinin/.rvm/gems/ruby-2.0.0-p598/gems/activesupport-4.2.1/lib/active_support/inflector/methods.rb:261:in `block in constantize'
......
............

Upvotes: 1

Views: 72

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

You can use association keyword to define association between two factories.

So, your factories should look like this:

FactoryGirl.define do
  factory :user do
    sequence(:name){ |i| "us#{i}" }
    sequence(:email){ |i| "us#{i}@ad.ad" }
    password 'qwerty'
    password_confirmation{ |u| u.password }
    association :status
  end
end

FactoryGirl.define do
  factory :status do
    sequence(:id){ |id| id }
    title 'user'
  end
end

association :status will ensure the association between user and status factories.

You can see more examples of factory_girl association here.

Upvotes: 1

Related Questions