ruby-on-rails 如何在Rails 7 Minitest中设置命名空间模型fixture?

olmpazwi  于 2023-03-24  发布在  Ruby
关注(0)|答案(1)|浏览(154)

我有一个类似的问题,比如this old one,它与在Rails 7中为has_one-belongs_to关联使用命名空间模型fixture有关。
关于ActiveRecord,在我的模型文件中,我已经:

# 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

关于fixtures,在我创建的test/fixtures/users.yml文件中,我成功地将以下内容用于User模型:

# test/fixtures/users.yml

foo:
  id: 1
  name: Foo
  email: foo@bar.com
  ...

bar:
  id: 2
  name: Bar
  email: bar@foo.com
  ...

然而,我在为Users::Setting模型设置fixture时遇到了麻烦。我尝试创建test/fixture/users/settings.yml文件,并使用以下命令,但没有成功:

# test/fixtures/users/settings.yml

_fixture:
  model_class: Users::Setting

foo_setting:
  id: 1
  user_id: 1
  ...

# foo_setting:
#   id: 1
#   user: foo
#   ...

当我运行一个测试时,我得到如下错误:
Minitest::UnexpectedError:ActiveRecord::Fixture::FixtureError:表“users”没有名为“user_id”/“user”的列。
在User fixture中,我也尝试使用以下代码,但得到了相同的Minitest错误:

# test/fixtures/users.yml

foo:
  id: 1
  name: Foo
  email: foo@bar.com
  setting: foo_setting (Users:Setting) # <<<
  ...

我也试着编辑test/test_helper.rb文件,但是我得到了同样的Minitest错误:

class ActiveSupport::TestCase
  fixtures :all
  set_fixture_class 'users/settings' => Users::Setting
end

在test/integration/user_flows_test.rb中,我已经:

# test/integration/user_flows_test.rb

require "test_helper"

class UserFlowsTest < ActionDispatch::IntegrationTest
  fixtures :users

  test "can something" do
    user = users(:foo)
    ...
  end
end

如何为命名空间的Users::Setting声明工作装置?

n3h0vuf2

n3h0vuf21#

找到了解决方案:
1.在test/test_helper.rb中添加了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

1.(Re)将包含fixture语句的文件命名为 users_settings.yml
1.在test/fixtures/users_settings.yml中找到了文件 users_settings.yml

相关问题