Question

Can't figure out why factory girl isn't generating my Question id's for me.

Factories:

users:

require 'faker'

FactoryGirl.define do
  factory :user do
    email {Faker::Internet.email}
    name {Faker::Name.name}
    password '12345678'
    password_confirmation '12345678'
  end
end

questions:

require 'faker'

FactoryGirl.define do
  factory :question do
    association :user
    title "Random question about Ruby on Rails"
    body { Faker::Lorem.paragraph(2) }
  end
end

Feature test

require 'spec_helper'

feature "Show questions" do

  given(:user) { FactoryGirl.create(:user) }    
  given(:question) { FactoryGirl.build(:question, user_id: user.id) }

  scenario 'guest user cannot visit edit question path' do
    visit edit_question_path(question)
    expect(current_url).to eq root_url
  end

...

end

Terminal fail:

ActionController::UrlGenerationError:
No route matches {:action=>"edit", :controller=>"questions", :format=>nil, 
:id=>#<Question id: nil, title: "Random question about Ruby on Rails", 
body: "Dolor in doloribus labore. Totam debitis eveniet v...", created_at: nil, updated_at: nil, user_id: 6309>} missing required keys: [:id]

I know the solution is out there, but I can't understand the problem. Thank you!

Was it helpful?

Solution

Using build creates an in memory object which has no database id yet

FactoryGirl.build(:question, user_id: user.id)

Using create will create the record in the database with an id

FactoryGirl.create(:question, user_id: user.id)

Your current code is trying to go the edit page for a Question that has never been saved

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top