I've a similar issue like this old one related to using namespaced model fixtures for a has_one-belongs_to association in Rails 7.
About ActiveRecord, in my model files I've:
# app/models/user.rb
class User < ApplicationRecord
has_one :setting, :class_name => 'Users::Setting', :foreign_key => 'user_id'
end
# app/models/users/setting.rb
class Users::Setting < ApplicationRecord
belongs_to :user, :class_name => 'User', :foreign_key => 'user_id'
end
# app/models/users.rb
module Users
def self.table_name_prefix
'users_'
end
end
About fixtures, in the test/fixtures/users.yml file I've created and successfully used the following for the User model:
# test/fixtures/users.yml
foo:
id: 1
name: Foo
email: foo@bar.com
...
bar:
id: 2
name: Bar
email: bar@foo.com
...
However I'm in trouble in setting up fixtures for the Users::Setting model. I tried to create the test/fixtures/users/settings.yml file and to use the following without success:
# test/fixtures/users/settings.yml
_fixture:
model_class: Users::Setting
foo_setting:
id: 1
user_id: 1
...
# foo_setting:
# id: 1
# user: foo
# ...
When I run a test, I get errors as follows:
Minitest::UnexpectedError: ActiveRecord::Fixture::FixtureError: table "users" has no columns named "user_id"/"user".
In the User fixtures I also tried to use the following but I get the same Minitest error:
# test/fixtures/users.yml
foo:
id: 1
name: Foo
email: foo@bar.com
setting: foo_setting (Users:Setting) # <<<
...
I also tried to edit the test/test_helper.rb file like so but I get the same Minitest error:
class ActiveSupport::TestCase
fixtures :all
set_fixture_class 'users/settings' => Users::Setting
end
In test/integration/user_flows_test.rb I've:
# test/integration/user_flows_test.rb
require "test_helper"
class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :users
test "can something" do
user = users(:foo)
...
end
end
How can I state working fixtures for the namespaced Users::Setting?
Found a solution:
set_fixture_class :users_settings => Users::Setting
test/test_helper.rb
class ActiveSupport::TestCase
...
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Namespaced models/fixtures
set_fixture_class :users_settings => Users::Setting
...
end