[rspec-users] Specify attr_protected

David Chelimsky dchelimsky at gmail.com
Wed May 30 19:43:29 EDT 2007


On 5/30/07, Jed Hurt <jed.hurt at gmail.com> wrote:
> This is kind of a two part question.
>
> Question One: I want to be sure that an Order model is protecting
> sensitive attributes from mass assignment.
>
> The example looks like this:
>
> describe Order do
>   it "should protect total attribute from mass assignment" do
>     @order = Order.new(:total => 0.05)
>     @order.total.should_not == 0.05
>   end
> end
>
> And the code to implement it:
>
> class Order < ActiveRecord::Base
>   attr_protected :total
> end
>
>
> It seems to work, but is there a better way? Not saying that this way
> is bad, just that I'm very green :)

This seems pretty good to me. You're not cluttering up the example
with what the value of total IS - just what it is not, which is the
thing you're interested in.

>
>
> Question Two: I actually have a bunch of attributes that need to be
> protected. Rather than hand-writing a call to the 'it' method for each
> attribute, could I just loop over an array of attributes that need to
> be checked and programatically define the 'it' calls?
>
> Pseudo-code:
>
> describe Order do
>   [:total, :id, :customer_ip, :status, :error_message, :updated_at,
> :created_at, :finalize, :tax, :shipping].each do |attribute|
>     it "should protect #{attribute} attributes from mass assignment" do
>       @order = Order.new(attribute => 'hax0rz')
>       @order.attribute.should_not == 'hax0rz'
>     end
>   end
> end
>
> What would the actual implementation look like?

I think it would look exactly like what you wrote. Have you tried it?


More information about the rspec-users mailing list