JGrishey
JGrishey

Reputation: 75

FactoryGirl undefined method `create='

I'm basically getting an error when I'm trying to use a factory I created for a Post model in Ruby on Rails.

Here's the full error:

 Failure/Error: post = create(:post)

 NoMethodError:
   undefined method `create=' for #<Post:0x007fbf1be6e510>
   Did you mean?  created_at=
 # ./spec/models/post_spec.rb:6:in `block (2 levels) in <top (required)>'

Here's the file for the factories:

spec/factories/post.rb

FactoryGirl.define do
    factory :post do
        title "Hello"
        content "Hello, my name is Jacob."
        user create(:user)
        user_id 1
    end
end

spec/models/post_spec.rb

require 'rails_helper'
require 'spec_helper'

describe Post do
    it "has a valid factory" do
        post = create(:post)
        expect(post).to(be_valid)
    end
end

I do have a spec/support/factory_girl.rb file which includes the FactoryGirl::Syntax::Methods. This file is loaded by spec/rails_helper.rb.

Also, the create(:user) line works and I'm able to use the user factory in the rails console, but not the post factory.

Any help would be fantastic. Thank you!

Upvotes: 2

Views: 1007

Answers (1)

Jon
Jon

Reputation: 10898

In your post factory, you have the syntax wrong for defining an associated record. Try defining it like this:

FactoryGirl.define do
  factory :post do
    title "Hello"
    content "Hello, my name is Jacob."
    user
  end
end

You just need to state that the post has a user, and you certainly shouldn't be setting them all to have a specific user_id ... since each post will create a new user unless told otherwise and you have no idea what user_id will be generated.

Upvotes: 2

Related Questions