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

有帮助吗?

解决方案

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) }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top