Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
Testing mass assignment with RSpec-Shoulda

If you’re new to Rails, or if you’ve been using Rails 2 for a long time, you might not be aware that Shoulda offers an allow_mass_assignment_of matcher that works just like it sounds. Here’s the example from the source code:

it { should_not allow_mass_assignment_of(:password) }
it { should allow_mass_assignment_of(:first_name) }

Having explicit tests for whether fields should be mass-assignable is probably safer than letting developers arbitrarily add or remove fields from the attr_accessible declarations — at least when they break a test they’ll have to think twice about it.

Comments
  1. bryanl says:

    _Having explicit tests for whether fields should be mass-assignable is probably safer than letting developers arbitrarily add or remove fields from the attr_accessible declarations — at least when they break a test they’ll have to think twice about it._

    I’m having a hard time digesting this. Shoulda matchers are basically the same thing as writing your implementation right in your test. Now, is this probably a good idea?

  2. Mark Rushakoff says:

    Hi Bryan,

    I think this helper shines most in the should *not* case. If I see some column `foo` that isn’t included in `attr_accessible`, it might not be immediately obvious for `foo` whether it was intentionally excluded. The test would clarify the intent.

    On the other hand, I think I can agree with you about the positive assertion test not being very valuable. If you have a field as `attr_accessible`, you probably have *some* test that depends on it being accessible.

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *