Reputation: 1329
I have two model classes in a "parent-chid" relationship, or association.
organizations
is the parent table / model having the attributes: id, organization_name, created_at and updated_at
.
events
is the child table / model having the attributes: id, event_description, host_name, created_at, updated_at and organization_id
.
The association between organizations and events records is events.organization_id = organizations.id
, or as is specified in the model classes:
class Event < ApplicationRecord
...
belongs_to :organization
...
end
class Organization < ApplicationRecord
...
has_many :events, :dependent => :destroy
...
end
The tests for organizations
model and organizations
controller runs without any errors.
The test for events
controller is not build yet.
The app fully functional and is working without any errors.
The problem I have is that I cannot make the Events model test to pass.
Here is my code.
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
I am trying to create an organization first and use the id
for the organization_id
attribute of the new event
to be created.
And this is the file 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
Basically I want to create first an organization
and use this id
to be assigned to organization_id
when I am creating and event
.
When running the test rspec spec/models/event_spec.rb
I am getting this error:
/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)
Don't know how to fix it or how to write a better test?
Upvotes: 0
Views: 722
Reputation: 1059
I think your event
factory should look a bit different:
FactoryGirl.define do
factory :event do
event_description { Faker::Lorem.sentence(3) }
host_name { Faker::Internet.domain_name }
organization { build(:organization) }
end
end
Upvotes: 0