rails attr_accessible rspec check
Asked Answered
B

1

6

When I want to test if attribute is / is not accessible with RSpec I'm doing it like this

class Foo
  attr_accesible :something_else
end

describe Foo do
  it('author should not be accessible')    {lambda{described_class.new(:author=>true)}.should raise_error ActiveModel::MassAssignmentSecurity::Error}
  it('something_else should be accessible'){lambda{described_class.new(:something_else=>true)}.should_not raise_error ActiveModel::MassAssignmentSecurity::Error}
end

is there better way doing that ?

...thx

Bicentenary answered 2/8, 2012 at 9:55 Comment(0)
T
7

This is the way attribute accessibility tests are done in the Rails Tutorial, which I think are pretty good. So, in your case, the test code could be modified slightly to read like:

describe Foo do
  describe "accessible attributes" do
    it "should not allow access to author" do
      expect do
        Foo.new(author: true)
      end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end

    it "should allow access to something_else" do
      expect do
        Foo.new(something_else: true)
      end.to_not raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end
  end
end

If this isn't what you were looking for, can you give us a better idea of what kind of solution you're after when you ask if there is a "better way"?

Edit

You may be interested in the Shoulda ActiveModel matchers, which would clean up the code to just one line per test. Something like:

it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }
Trahan answered 7/8, 2012 at 15:51 Comment(4)
+1 for those shoulda matchers, I thought should don't have those two... worksBicentenary
This question was actually responsible for me finding out about the shoulda matchers, so thanks for asking it. I went and refactored some of my test code to use them.Trahan
If you found the question useful, then please vote it up! The author deserves it.Forster
@Hosam Aly, you're absolutely right, and that was an oversight on my part. Question upvoted.Trahan

© 2022 - 2024 — McMap. All rights reserved.