Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `stringify_keys' while using Factory Girl

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

 @user = { username:'newuser',
           email:'[email protected]',
           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 '[email protected]'
  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

like image 759
vinc386 Avatar asked Apr 01 '26 17:04

vinc386


2 Answers

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.

like image 146
rowanu Avatar answered Apr 04 '26 09:04

rowanu


We need to see an example of a failing test to diagnose, but here is one thing that can cause it – sending an object when attributes are required. I once fixed one of my failing tests by changing:

post :create, organization: @organization

to

post :create, organization: @organization.attributes
like image 33
Peter DeWeese Avatar answered Apr 04 '26 07:04

Peter DeWeese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!