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

1 Answer 1

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) } 
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for those shoulda matchers, I thought should don't have those two... works
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.
If you found the question useful, then please vote it up! The author deserves it.
@Hosam Aly, you're absolutely right, and that was an oversight on my part. Question upvoted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.