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

橙三吉。 提交于 2019-12-03 04:53:49

问题


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!


回答1:


How about running this?

rake db:test:load

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




回答2:


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


来源:https://stackoverflow.com/questions/4949319/factorygirl-rspec-rails-3-undefined-method-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!