测试指向自身的模型 rspec rails 5

test for models that points itself rspec rails 5

我刚开始在 Ruby 上 Rails 进行单元测试,所以我在测试中需要一些帮助。

这是我的模型User.rb

class User < ApplicationRecord
  belongs_to :created_by, foreign_key: :created_by_id, class_name: 'User'
end

我想创建一个测试来验证此关联。我尝试在我的 user_spec.rb

上这样做
describe 'should validates associations' do
  subject { User.new }
  it { should belong_to(subject.created_by) }
end

这是错误响应

Failures:

1) User should validates associations should belong to Failure/Error: it { should belong_to(subject.created_by) } Expected User to have a belongs_to association called (no association > called ) # ./spec/models/user_spec.rb:17:in `block (3 levels) in '

您为匹配器提供了一个实例,但它等待引用名称和引用的 class 名称。您的测试应该如下所示。

it { should belong_to(:created_by).of_type(User) } 

ActiveRecord shoulda matchers 不需要为 运行 的测试实例化 class 的任何对象。在这里,您已经初始化了一个新的 User 实例作为主题,并尝试将其传递给 shoulda 匹配器以检查 belongs_to 关联。
但是,为了检查具有特定外键和 class 名称的模型上的 belongs_to 关联,可以使用以下测试:

it { should belong_to(:created_by).with_foreign_key(:created_by_id).class_name('User') }

除了上面提到的两个之外,ActiveRecord 匹配器还有很多其他选项。 Shoulda code on GitHub

中详细记录了这些选项