Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relation does not exist when running rspec tests

I have this in my group_spec.rb file:

describe Group do
  it { should have_many(:users) }
end

and this in my user_spec.rb file:

describe User do
  it { should belong_to(:group) }
end

When I run the tests, I get:

Failure/Error: it { should have_many(:users) }
ActiveRecord::StatementInvalid:
PGError: ERROR:  relation "users" does not exist

   LINE 4:              WHERE a.attrelid = '"users"'::regclass
                                           ^
   :             SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
                 FROM pg_attribute a LEFT JOIN pg_attrdef d
                   ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                WHERE a.attrelid = '"users"'::regclass
                  AND a.attnum > 0 AND NOT a.attisdropped
                ORDER BY a.attnum

In my group.rb file I have:

has_many :users

And in my users.rb file I have:

belongs_to :group

I feel like I'm missing something that should be obvious. Any help would be appreciated. Thanks!

John

like image 636
John Avatar asked Nov 28 '11 21:11

John


2 Answers

Had this same problem and used the solution in the comment from cuvius. Posting here so that people don't miss it!

Run: RAKE_ENV=test rake db:migrate:reset db:test:prepare to set up your test database.

like image 54
apb Avatar answered Nov 13 '22 13:11

apb


Unfortunately rake db:test:prepare is deprecated in rails 4+ so it's not best solution now.
I guess that in your user factory class written as User. The problem occurs because factories loads before migrations done.
So to solve this:
Change in your factory class name from

factory :user, class: User do
  # ...
end

to

factory :user, class: 'User' do
  # ...
end
like image 35
CarefreeSlacker Avatar answered Nov 13 '22 11:11

CarefreeSlacker