使用 RSPEC 测试 child 模型并获取错误 undefined method id

Testing child model with RSPEC and getting the error undefined method id

我有两个模型 类 "parent-chid" 关系或关联。

organizations 是具有以下属性的 parent table / 模型:id, organization_name, created_at and updated_at.

events 是具有以下属性的 child table / 模型:id, event_description, host_name, created_at, updated_at and organization_id.

组织和事件记录之间的关联是 events.organization_id = organizations.id,或者如模型中指定的那样 类:

class Event < ApplicationRecord
...
  belongs_to :organization
...
end

class Organization < ApplicationRecord
...
  has_many  :events, :dependent => :destroy
...
end

organizations 模型和 organizations 控制器的测试运行没有任何错误。 events 控制器的测试尚未构建。 该应用程序功能齐全,运行无任何错误。

我遇到的问题是无法通过事件模型测试。

这是我的代码。

factories/organizations

FactoryGirl.define do
  factory :organization do
    organization_name { Faker::Company.name }
  end
  factory :invalid_organization, class: Organization do
    organization_name ''
  end
end

factories/events

FactoryGirl.define do
  factory :event do
    event_description { Faker::Lorem.sentence(3) }
    host_name { Faker::Internet.domain_name }
    organization = build(:organization)
    organization_id = organization.id
  end
end

我正在尝试先创建一个组织,然后使用 id 作为要创建的新 eventorganization_id 属性。

这是文件 event_spec.rb

require 'rails_helper'

RSpec.describe Event, type: :model do
  it "has a valid factory" do
    event = build(:event)
    expect(event).to be_valid
  end
  it { is_expected.to validate_presence_of(:event_description) }
  it { is_expected.to validate_presence_of(:host_name) }
  it { is_expected.to validate_presence_of(:organization_id) }
  it { is_expected.to belong_to(:organization) }
end

基本上我想先创建一个 organization 并在创建时使用此 id 分配给 organization_idevent.

当 运行 测试 rspec spec/models/event_spec.rb 我得到这个错误:

/Users/levi/ror/events-handler/spec/factories/events.rb:6:in `block (2 levels) in <top (required)>': undefined method `id' for #<FactoryGirl::Declaration::Static:0x007febc03db798> (NoMethodError)

不知道如何修复它或如何编写更好的测试?

我认为你们的 event 工厂看起来应该有点不同:

FactoryGirl.define do
  factory :event do
    event_description { Faker::Lorem.sentence(3) }
    host_name { Faker::Internet.domain_name }
    organization { build(:organization) } 
  end
end