Search code examples
ruby-on-railsrspecruby-on-rails-3.1factory-botstringify

undefined method `stringify_keys' while using Factory Girl


I have the following block of code in my User_spec.rb:

 @user = { username:'newuser',
           email:'new@user.com',
           fname:'new',
           lname:'user',
           password:'userpw',
           password_confirmation:'userpw'}

for creating a using using these attributes. However while I moved all these attributes to Factories.rb:

require 'factory_girl'

Factory.define :user do |u|
  u.username 'newuser'
  u.email 'new@user.com'
  u.fname 'new'
  u.lname 'user' 
  u.password 'newuserpw'
  u.password_confirmation 'newuserpw'
end

and replace the line in user_spec.rb with:

@user = Factory(:user)

all my tests that related to the User model failed(such as tests for email, password, username etc), all were giving me

"undefined method `stringify_keys' for…"

the new user object


Solution

  • I had a similar problem, and it was because I was passing a FactoryGirl object to the ActiveRecord create/new method (whoops!). It looks like you are doing the same thing here.

    The first/top @user you have listed is a hash of values, but the second/bottom @user is an instance of your User ojbect (built by FactoryGirl on the fly).

    If you are calling something like this in your specs:

    user = User.new(@user)
    

    The first (hashed) version of @user will work, but the second (objectified) version will not work (and throw you the 'stringify_keys' error). To use the second version of @user properly, you should have this in your specs:

    user = Factory(:user)
    

    Hope that helps.