Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 674
dearlbry Avatar asked Feb 09 '11 19:02

dearlbry


2 Answers

How about running this?

rake db:test:load

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

like image 114
TK-421 Avatar answered Nov 18 '22 11:11

TK-421


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
like image 41
stream7 Avatar answered Nov 18 '22 09:11

stream7