title: How to test inserting a has_many relation with spec?
body: <p>I'm inserting a User in a Page (a page has many users through memberships table), and I'm expecting it to fail since a Role is required. I have validate_presence_of on user, page and role on the membership (join table).</p>
  
  <p>My issue is that the test breaks before it reaches the end, because an exception is thrown. So I thought, I'll add an 'expect raise' to it</p>
  
  <pre><code>it 'should not be valid without a role' do
    user = FactoryGirl.build(:user)
    expect { page.users &lt;&lt; user }.to raise_error(ActiveRecord::RecordInvalid)
  end
  </code></pre>
  
  <p>But this doesn't really test, that the error was caused by the lack of Role (Validation error: No Role provided). Is there a better way to test this? Or is there a way to set the user in the page.users without saving it, and then check if page is valid?</p>
  
  <p>Update:</p>
  
  <p>This does not work either (exception is thrown on page.users &lt;&lt; users, invalid active record, role must be provided):</p>
  
  <pre><code>it 'should not be valid without a role' do
    user = FactoryGirl.build(:user)
    page.users &lt;&lt; user
    page.should have(1).error_on :role
  end
  </code></pre>
  
  <p>Update 2:</p>
  
  <p>I think I have the answer, this works for now</p>
  
  <pre><code>it 'should not be valid without a role' do
    user = FactoryGirl.build(:user)
    expect { page.users &lt;&lt; user }.to raise_error(ActiveRecord::RecordInvalid, /Role must be provided/)
  end    
  </code></pre>