0

I've got a model that is analogous to the Categories model discussed in this previous discussion of many-to-many relationships. Briefly, I have many stock categories (~200 categories) that I want to be loaded for all users. I want the has_and_belongs_to_many relationship so I can easily find those users that have the various categories and count the number of users with each category. If a user deletes their use of a category, I need it to be available for others, even if no one is using it.

I've gotten it to work in the console and in development mode, but it doesn't seem to be working in test mode, which makes me think there must be a better way of doing this.

In db/seeds.rb, I have an array...

c = [ "Category 1", "Category 2", "Category 3", "Category 4" ]
c.each { |cat| Category.create!(category: cat)}

I know that there is a problem in test mode because if I include...

$stdout.print Category.first.category

in a test, I get...

Error:
CategoryTest#test_should_be_valid:
    NoMethodError: undefined method `category' for nil:NilClass
    test/models/category_test.rb:17:in `block in <class:CategoryTest>'

Alternatively, if I do...

Category.create!(category: "Category 5")
$stdout.print Category.first.category

It outputs Category 5.

Any ideas on a better way of initializing Category objects and how I can get it to be seen in test mode?

PD Schloss
  • 149
  • 5
  • development and test have two different databases, you need to run the seeds as well on the test database. -> `RAILS_ENV rake db:seed` – Mahmoud Sayed Jan 02 '19 at 22:46
  • That doesn't seem to do anything. Is there a way to initialize it in the model's test fixture? – PD Schloss Jan 02 '19 at 23:32

2 Answers2

0

The db seed is not a feature designed for test purpose.

You can use test fixtures(the rails build in one)

https://guides.rubyonrails.org/testing.html

or factory_bot_rails to fill test data into your test database before you start every unit test

https://github.com/thoughtbot/factory_bot_rails 
teddylee
  • 21
  • 3
0

If you really want to do this via seeds try RAILS_ENV=test rake db:seed (or db:reset if you're not sure if your test DB is on the up and up.

This can get you going with some data, but it isn't a great way to setup test data. I'd recommend checking out some approaches where you set the data up in the test, or look at Rails fixtures capabilities.

naveed
  • 68
  • 3
  • 7