FactoryGirl + RSpec + Rails 3 'undefined method <attribute>='
Asked Answered
K

2

24

I'm fairly new to rails and TDD (as will no doubt be obvious from my post) and am having a hard time wrapping my brain around Rspec and FactoryGirl.

I'm using Rails 3, rspec and factory girl:

gem 'rails', '3.0.3'
# ...   
gem 'rspec-rails', '~>2.4.0'
gem 'factory_girl_rails'

I have a user model that I've been successfully running tests on during development, but then needed to add an attribute to, called "source". It's for determining where the user record originally came from (local vs LDAP).

In my factories.rb file, I have several factories defined, that look something like the following:

# An alumnus account tied to LDAP
Factory.define :alumnus, :class => User do |f|
  f.first_name "Mickey"
  f.last_name  "Mouse"
  f.username   "mickeymouse"
  f.password   "strongpassword"
  f.source     "directory"
end

I have a macro defined (that's been working up until now) that looks like this:

def login(user)
  before(:each) do
    sign_out :user
    sign_in Factory.create(user)
  end
end

I'm calling it in multiple specs like so (example from users_controller_spec.rb):

describe "for non-admins or managers" do
  login(:alumnus)

  it "should deny access" do
    get :index
    response.should redirect_to(destroy_user_session_path)
  end

end

If I don't specify the "source" attribute, everything works OK, but as soon as I do, I get an error like so when running the test

  12) UsersController for non-admins or managers should deny access
 Failure/Error: Unable to find matching line from backtrace
 NoMethodError:
   undefined method `source=' for #<User:0x00000100e256c0>

I can access the attribute no problem from the rails console and the app itself, and it's listed in my attr_accessible in the user model. It's almost as though Rspec is seeing an old version of my model and not recognizing that I've added an attribute to it. But if I put the following line into my user model, the error disappears

attr_accessor :source

... which indicates to me that it is actually looking at the correct model.

Help!

Kaleidoscope answered 9/2, 2011 at 19:7 Comment(0)
F
58

How about running this?

rake db:test:load

[If you added a new attribute you'd need to migrate it to the test database.]

Fourteenth answered 9/2, 2011 at 19:12 Comment(1)
Was breaking my head over this for a couple of hours.. I'd removed the line from the spec_helper which tested for pending migrations as it should have been deprecated and unnecessary. Turns out it's not that unnecessary.. Fixed it by running RAILS_ENV=test bin/rake db:drop db:create db:migrateSoapberry
D
6

if you don't use schema.rb (e.g. you have set config.active_record.schema_format = :sql) you should run

rake db:test:prepare
Disraeli answered 15/6, 2011 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.