Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 465
user929062 Avatar asked Jul 18 '13 15:07

user929062


People also ask

What is Factorybot in RSpec?

Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl.

What is Factorybot used for?

Factory Bot is often used in testing Ruby on Rails applications; where it replaces Rails' built-in fixture mechanism. Rails' default setup uses a pre-populated database as test fixtures, which are global for the complete test suite.


1 Answers

Not an answer but a suspicition... you probably shouldn't write the spec the way you are doing it.

in your spec do something like:

u=FactoryGirl.create(:user)
User.where('id=?',u.id).count.should == 1

Making your tests dependent on specific ids is a recipe for disaster.

like image 199
timpone Avatar answered Oct 07 '22 14:10

timpone