Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails attr_accessible rspec check

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

like image 275
equivalent8 Avatar asked Aug 02 '12 09:08

equivalent8


1 Answers

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) }
like image 73
Paul Fioravanti Avatar answered Oct 03 '22 22:10

Paul Fioravanti