[LRUG] Cucumber and mass assignment whitelisting

Sam Stokes webstuff-lrug at samstokes.co.uk
Tue Feb 16 01:01:53 PST 2010


Something I've done in the past is put the following definition for 
"please_new" in my spec/spec_helper.rb / features/support/env.rb / etc. 
  It doesn't help with machinist, but it's useful if your test setup is 
manually instantiating models:

   module ActiveRecordExtensions
     module ClassMethods
       # Like new but bypassing attr_protected, for test setup purposes
       # only: allows succinct creation of AR models without having to
       # special-case the protected attributes for each model differently.
       def please_new(opts = {})
         new do |object|
           opts.each do |attribute, value|
             object.send("#{attribute}=", value)
           end
         end
       end
     end

     def self.included(other)
       ActiveRecord::Base.send(:extend, ClassMethods)
     end
   end

Then in your spec before block (or whatever) you can say

   @user = User.please_new(:name => "bob", :password => "secret")

Testing purists would probably point out that now you're testing code 
that doesn't run in production, but unless the instantiation itself is 
the tricky part you're testing I'd argue that maybe doesn't matter.

-- 
Sam

Jay Caines-Gooby wrote:
> Hiya,
> 
> I'm a long time lurker. I'm doing The Right ThingTM with a new project
> and it's Cucumber, Machinist, Haml and Sass all the way. Loving Sass
> mixins!
> 
> My question:
> 
> If I'm white-listing my model attributes from mass-assignment with an
> initializer in security.rb:
> 
> ActiveRecord::Base.send(:attr_accessible, nil)
> 
> my tests fail horribly, because cucumber, machinist et al are using
> mass assignment to create the test objects.
> 
> Is there a way to make the two play nicely together?
> 
> 



More information about the Chat mailing list