我在页面中插入了一个用户(一个页面通过成员资格表有很多用户),我希望它会失败,因为需要一个角色。我在成员资格(加入表)上的用户、页面和角色上有 validate_presence_of。
我的问题是测试在结束之前就中断了,因为抛出了异常。所以我想,我会加一个“预期加薪”
it 'should not be valid without a role' do
user = FactoryGirl.build(:user)
expect { page.users << user }.to raise_error(ActiveRecord::RecordInvalid)
end
但这并没有真正测试,该错误是由缺少角色引起的(验证错误:未提供角色)。有没有更好的方法来测试这个?或者有没有办法在page.users中设置用户而不保存,然后检查页面是否有效?
更新:
这也不起作用(page.users << users 上抛出异常,无效的活动记录,必须提供角色):
it 'should not be valid without a role' do
user = FactoryGirl.build(:user)
page.users << user
page.should have(1).error_on :role
end
更新 2:
我想我有答案了,这暂时有效
it 'should not be valid without a role' do
user = FactoryGirl.build(:user)
expect { page.users << user }.to raise_error(ActiveRecord::RecordInvalid, /Role must be provided/)
end