rept
rept

Reputation: 2236

How to get the created FactoryGirl objects?

I have these models:

class User < ActiveRecord::Base
  has_many :company_users, :dependent => :delete_all

class Company < ActiveRecord::Base
  has_many :company_users, :dependent => :delete_all
  has_many :users, :through => :company_users

class CompanyUser < ActiveRecord::Base
  belongs_to :company
  belongs_to :user

I use this helper function to create and login:

def create_company_admin
  company_user = FactoryGirl.create(:company_user, :has_shopper, :has_company, :admin)
  user = User.first
  login_as user, scope: :user
  company_user
end

And this is the actual test

feature 'user listing' do
  background do
    company_user = create_company_admin
  end
  scenario 'getting user list' do
    visit '/companies'
    page.has_content? company_user.user.name
  end
end

This works until where he calls: company_user.user.name which doesn't seem to exist. There I get undefined local variable or method `company_user'

This is the factory:

factory :company_user, class: CompanyUser do
  authorized true

  trait :admin do
    admin true
  end

  trait :not_admin do
    admin false
  end

  trait :has_shopper do
    association :user, factory: :shopper
  end

  trait :has_company do
    association :company, factory: :company
  end
end

Edit:

This is the factory of shopper (which is a kind of user)

factory :shopper, class: User do
  username "user"
  email "[email protected]"
  password "password1"
  after(:create) do |u|
    u.skip_confirmation!
    u.save!
  end
end

How do I get the user, company and company_user in the test?

Upvotes: 1

Views: 535

Answers (1)

andreofthecape
andreofthecape

Reputation: 1196

In your helper you create an company_user. But company_user belongs to user and I dont see you creating a user (you call user = User.first after creating company_user but that would be nil).

I also don't see you creating a company. Create the user in the helper using a factory first, then a company and then the company_user (referencing the user).

You can then access them in your tests with user = User.first, company = Company.first and company_user = CompanyUser.first

Upvotes: 1

Related Questions