使用RSPEC测试子模型并获取错误未定义的方法ID

时间:2016-12-08 15:36:16

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

我在“父 - chid”关系或关联中有两个模型类。

organizations是具有以下属性的父表/模型:id, organization_name, created_at and updated_at

events是具有以下属性的子表/模型: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创建新organization_id的{​​{1}}属性。

这是文件event

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_id

运行测试时event我收到此错误:

rspec spec/models/event_spec.rb

不知道如何解决它或如何编写更好的测试?

1 个答案:

答案 0 :(得分:0)

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

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