【问题标题】:Error testing ActiveRecord association测试 ActiveRecord 关联时出错
【发布时间】:2018-05-09 21:28:35
【问题描述】:

我有一个带有以下型号的 Rails 5.2 应用程序:

class Foo < ApplicationRecord
  has_many :bars
end

class Bar < ApplicationRecord
  belongs_to :foo
end

我正在使用 rspec-rails (3.7.2)、shouda-matchers (3.1.2)。 我有一个测试关联的规范:

describe Foo do
  it { is_expected.to have_many :bars }
  it { should have_many :bars }
end

无论我使用哪种语法,我都会得到相同的错误:

Foo should have many :bars
Failure/Error: it { is_expected.to have_many :bars }
  expected #<Foo:0x007f9f813ce650> to respond to `has_many?` # ./spec/models/foo_spec.rb:4

Foo should have many :bars
Failure/Error: it { should have_many :bars }
  expected #<Foo:0x007f9f84ad3970> to respond to `has_many?` # ./spec/models/foo_spec.rb:5

我按照here 的说明进行操作,但仍然出现错误。我已经将我的示例项目推送到 Github:https://github.com/fredwillmore/shoulda_matchers_test

【问题讨论】:

    标签: ruby-on-rails rspec-rails shoulda


    【解决方案1】:

    我不确定,但我认为您需要定义 rspec 的类型,例如:

    RSpec.describe Foo, type: :model do
       it { is_expected.to have_many :bars }
    end
    

    【讨论】:

    • 我已将 rspec 配置为从目录名称推断类型,因此只要规范位于名为 'models' 的目录中,类型自动为 :model
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多