Testing child model with RSPEC and getting the error undefined method id
<p>I have two model classes in a "parent-chid" relationship, or association.</p>

<p><code>organizations</code> is the parent table / model having the attributes: <code>id, organization_name, created_at and updated_at</code>.</p>

<p><code>events</code> is the child table / model having the attributes: <code>id, event_description, host_name, created_at, updated_at and organization_id</code>.</p>

<p>The association between organizations and events records is <code>events.organization_id = organizations.id</code>, or as is specified in the model classes:</p>

<pre><code>class Event &lt; ApplicationRecord
...
  belongs_to :organization
...
end

class Organization &lt; ApplicationRecord
...
  has_many  :events, :dependent =&gt; :destroy
...
end
</code></pre>

<p>The tests for <code>organizations</code> model and <code>organizations</code> controller runs without any errors. 
The test for <code>events</code> controller is not build yet. 
The app fully functional and is working without any errors.</p>

<p>The problem I have is that I cannot make the Events model test to pass.</p>

<p>Here is my code.</p>

<p><code>factories/organizations</code></p>

<pre><code>FactoryGirl.define do
  factory :organization do
    organization_name { Faker::Company.name }
  end
  factory :invalid_organization, class: Organization do
    organization_name ''
  end
end
</code></pre>

<p><code>factories/events</code></p>

<pre><code>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
</code></pre>

<p>I am trying to create an organization first and use the <code>id</code> for the <code>organization_id</code> attribute of the new <code>event</code> to be created.</p>

<p>And this is the file <code>event_spec.rb</code></p>

<pre><code>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
</code></pre>

<p>Basically I want to create first an <code>organization</code> and use this <code>id</code> to be assigned to <code>organization_id</code> when I am creating and <code>event</code>.</p>

<p>When running the test <code>rspec spec/models/event_spec.rb</code> I am getting this error: </p>

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

<p>Don't know how to fix it or how to write a better test?</p>