Rails fixture 无法识别 belongs_to 关系

Rails fixture doesn't recognize a belongs_to relationship

我有 2 个模型:

class User < ApplicationRecord
  has_many :games, dependent: :nullify
class Game < ApplicationRecord
  belongs_to :user
  belongs_to :playlist, optional: true

在我的赛程中,游戏只有 belongs_to 位用户。我唯一的固定装置是:

user.yml

michel:
  id: 1
  pseudo: michelchardou
  email: mich@chardou.com
  encrypted_password: User.digest('password')
  admin: false

game.yml

game1:
  user: michel
  token: 123456
  total_score: 0

我的基本测试适用于

  test "should get expected game fixture token" do
    assert_equal '123456', @game1.token
    assert_equal 0, @game1.total_score
  end

但以下会引发错误:

  test "should get expected game fixture user" do
    assert_equal 'michel', @game1.user
  end

错误是:

Failure:
GameTest#test_should_get_expected_game_fixture_user [/Users/pierre/code/pierregarciafr/wadzatsong/test/models/game_test.rb:25]:
Expected: "michel"
  Actual: nil

为什么?

那是因为您手动分配了您的用户 (michel) 将拥有的 ID,您应该将其留给 Rails(或 ORM),尝试删除该行。

用户 michel 的 fixture 应该是这样的:

michel:
  pseudo: michelchardou
  email: mich@chardou.com
  encrypted_password: User.digest('password')
  admin: false

另一方面,您的第一个示例没有问题,因为您没有测试两个模型之间的关系,而是检查明确添加到夹具文件的内容。