How to create a model with a certain id using rspec and factory girl

user929062 picture user929062 · Jul 18, 2013 · Viewed 15.5k times · Source

I use:

gem 'rails', '3.2.11'
gem 'rspec-rails', '2.13.2'
gem 'webrat', '0.7.3'
gem 'factory_girl_rails', '4.1.0'
gem 'spork', '~> 0.9.0.rc'

I want to test my HP where I always have a link to a certain user, so the pages controller for HP contains:

@user = User.find(7)

And the view HP contains:

link_to 'See user', @user

The problem is that all tests fail since test database has no user with id 7. I tried:

FactoryGirl.define do
  factory :user do
    name "Testuser"
    id "7"
  end
end

... but this doesn't work. There is always the error:

The spec is this:

describe "GET 'home'" do

    before(:each) do
      FactoryGirl.create(:user)
    end

    it "should be successful" do
      get 'home'
      response.should be_success
    end
end

Failure/Error: get 'home' ActiveRecord::RecordNotFound: Couldn't find User with id=7

The HP is working fine in reality, just the test fails. How can I assure this test is not going to fail?

Answer

James Chevalier picture James Chevalier · Jul 18, 2013

Based on the Using Factories section of the documentation, I would set the id in the spec itself with something like:

@user = FactoryGirl.create(:user, :id => 7)