rspec - How to avoid Persistence of a Factory Girl object -


i have several rspec tests use factory_girl. used on mongodb mongoid in rails 3 app.

somewhere along line, test against invalid values: expecting validation-errors. after that, anytime call factory(:user), fails, because of validation errors. expect entirely new , clean object, when call factory(:user), not re-used, battered one.

example code below, illustrates *user_spec.rb* adding invalid items "roles". user model marks record invalid.

a little further in specs, *sidebar_helper_spec.rb* need instantiate @user, , there fails, telling me invalid role "foo" there. can see role not present in factory.rb.

is expected behaviour? can toggle persistence (or caching?) config option?

## models/user_spec.rb  require 'spec_helper' describe user   describe 'roles'     before(:each)       @user = factory.build(:user)     end     'should require role'       @user.roles = nil       @user.should_not be_valid     end     'should allow 1 role set of defined roles'       #@user.roles preset in factory "jobseeker"       @user.should be_valid     end     'should reject undefined roles'       @user.roles << "foo"       @user.should_not be_valid     end     'should allow multiple roles'       @user.roles = ["banned", "jobseeker"]       @user.should be_valid     end   end end  ## helpers/sidebar_helper_spec.rb  require 'spec_helper' describe sidebarhelper   before(:each)     @user = factory.create(:user) #fails mongoid::errors::validations: validation failed - roles foo invalid role.     @profile = factory.create(:profile)   end    # has many specs, fail on error in before(:each) end  ## actual factory.rb  factory.define :user |f|   f.password    'mischief managed'   f.email       'h.potter@gryffindor.hogwards.edu.wiz'   f.roles       ['jobseeker'] end factory.define :employer |f|   f.password    'butterscotch'   f.email       'dumbledore@staff.hogwards.edu.wiz'   f.roles       ['employer'] end  factory.define :profile |f|   f.available true   f.sync false end 

= creates new array ["banned", "jobseeker"] , sets @user.roles:

# should allow multiple roles @user.roles = ["banned", "jobseeker"] 

but << appends "foo" existing array (i.e. modifies existing array!):

# should reject undefined roles @user.roles << "foo" 

factorygirl not reusing same user object, re-using same roles attribute. change roles array dynamically created each time in factory:

factory.define :user |f|   ...   f.roles       { ['jobseeker'] } end factory.define :employer |f|   ...   f.roles       { ['employer'] } end 

either this, or avoid using << or method changes existing array/variable, , instead use = uses new object. e.g.

# should reject undefined roles @user.roles = [ "foo" ] 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -