Rspec 未定义的方法 `belong_to'

Rspec undefined method `belong_to'

我正在使用 RSpec 3.10 并尝试测试 belongs_to 关系

RSpec.describe MyClasss, type: :model do
  it { is_expected.to belong_to(:another_class) }
end

NoMethodError:
  undefined method `belong_to' for #<RSpec::ExampleGroups::MyClasss

我需要特殊配置才能使用 belong_to 匹配器吗?

您应该安装 shoulda-matchers gem

https://github.com/thoughtbot/shoulda-matchers

就我而言,我的测试设置不正确。这是我的:

describe MyModel do

这是有效的方法:

RSpec.describe MyModel, type: :model do