3

Using Rails 3.2.18 and Postgres, I have a few tables for which I have created a view to minimize the data loaded by ActiveRecord. Everything appears to be running correctly when in the application, but when I try to run Rspec I get:

 ActiveRecord::StatementInvalid:
       PG::UndefinedTable: ERROR:  relation "properties_view" does not exist

(where 'properties_view' is the view on the 'properties' table)

What can I do to ensure that Rspec loads views properly from Postgres?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Ivar
  • 5,102
  • 2
  • 31
  • 43
  • possibly related to http://stackoverflow.com/questions/21576686/pgundefinedtable-error-relation-does-not-exist-with-a-correct-rails-naming – Ivar Jul 09 '14 at 21:14
  • 1
    Are you use a `schema.rb` or `structure.sql` file to keep track of your database structure? – mu is too short Jul 09 '14 at 21:26
  • @muistooshort yes! Thank you - that is a very insightful question. I do have a schema.rb file and it does not include the views! I will investigate further. – Ivar Jul 09 '14 at 23:58

2 Answers2

7

Rails doesn't really understand "advanced" database concepts like views so they won't appear in your schema.rb. When rspec is setting up its test database, it will use schema.rb to create the database schema, since you won't find your views in schema.rb, you won't find your views in the test database that rspec will be using and everything falls apart.

The solution is to switch from schema.rb to structure.sql. You should be able to update your config/application.rb to say:

config.active_record.schema_format = :sql

and then do a rake db:structure:dump to generate the structure.sql file. Once you have that, remove schema.rb from your file system and revision control, add structure.sql, and try again.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • I can always count on learning something from SO. :) I assume this could have database-dependent stuff? Caveat emptor. – zetetic Jul 10 '14 at 00:37
  • @zetetic: Yes, `structure.sql` will be database dependent but (a) so are views and (b) database portability is largely a myth unless you do it the hard way (i.e. by hand the hard way). – mu is too short Jul 10 '14 at 01:06
1

If you don't want to switch to the SQL schema format, using the scenic gem may help (Scenic Gem Gitub).

They allow you to add SQL Views (also materialized) to migrations and also adds them to your ruby schema.

Worked for me like a charm.

snrlx
  • 4,987
  • 2
  • 27
  • 34