Understanding specs and fixtures

I’ve got a plugin that needs to seed some groups.

Following, How to add new webhooks and customize webhook payload , in plugin.rb I have

  SeedFu.fixture_paths << Rails.root.join("plugins", "discourse-pfaffmanager", "db", "fixtures").to_s

I have stuff like this in db/fixtures/001_create_pfaffmanager_groups

Group.seed do |g|
  g.name = SiteSetting.pfaffmanager_ec2_pro_server_group
  g.visibility_level = Group.visibility_levels[:owners]
end

If I run a ./bin/rake db:migrate it does what I expect, but when I run the specs I get

#   ERROR:  duplicate key value violates unique constraint "index_groups_on_name"

So it seems like the specs want to run and re-run these seeds? That doesn’t make sense, as if I re-run the migration, they don’t cause errors then.

Maybe I should move those specs into spec/fixtures and have the plugin create those groups on startup? Is that best practice? I think I like the idea of having those groups getting created on migration better than asserting them with Group.find_or_create_by on every plugin startup, but that’s working.

Also, ./bin/rake db:drop db:create db:migrate seems to create the test database, but isn’t doing the migrations unless I do a RAILS_DB=test ./bin/rake db:migrate is that expected? I thought it would do those migrations.

Now I’m even more confused, even after the above migrate of the test db, I get

ActiveRecord::StatementInvalid:
  PG::UndefinedTable: ERROR:  relation "groups" does not exist
  LINE 8:  WHERE a.attrelid = '"groups"'::regclass

And I see stuff like this in from when I ran the migrate:

-- execute("UPDATE groups\nSET flair_icon = 'fab-youtube'\nWHERE flair_icon = 'youtube-play' OR flair_icon = 'fa-youtube-play'\n")

Well, I did a

./bin/rake db:test:prepare

and that fixed it, but I don’t remember having to do that before.

2 Likes