Reputation: 129
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
Upvotes: 3
Views: 3645
Reputation: 5962
@rowanu Answered your question, but let me layout my example too for future reference:
What was failing in my case was:
@user = User.new user_attr
@user.bookings_build(Booking.new booking_attr)
Note that I am trying to build with a booking instance and not hash of attributes
The working example:
user_attr_hash = FactoryGirl.attributes_for(:user)
booking_attr_hash = FactoryGirl.attributes_for(:booking)
@user = User.new user_attr_hash
@user.bookings.build(booking_attr_hash)
And in spec/factories/domain_factory.rb I have
FactoryGirl.define do
factory :user do
# DEFAULT USER...
password "123123123"
email "[email protected]"
# there rest of attributes set...
end
factory :booking do
start_date Date.today
end_date Date.today+3
# the rest of attributes
end
end
Upvotes: 0
Reputation: 18333
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
Upvotes: 2
Reputation: 1722
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.
Upvotes: 4