当返回的消息是'ActiveRecord :: RecordInvalid'时,为什么这个rspec'期望raise_error'失败?

时间:2016-02-17 11:14:08

标签: ruby-on-rails rspec

以下rspec测试失败,但与失败测试一起提供的消息似乎是预期的结果。

describe '#validate_maximum_pending_actions_not_been_reached' do
  let(:action) { build :action, status: 'pending' }
  before :each do
    10.times do
      create :action, status: 'pending'
    end
  end
  it 'does not save the 11th action' do
    expect(action.save).to raise_error #(ActiveRecord::RecordInvalid,'Validation failed: maximum number of pending actions already reached')
  end
end


Failure/Error: let(:action) { build :action, status: 'pending' }
  ActiveRecord::RecordInvalid:
    Validation failed: maximum number of pending actions already reached

我通过省略错误消息尝试不那么具体,只是期望测试将raise_error。测试仍然失败,但是上面的描述表明确实存在错误。

我做错了什么?

正在测试的方法如下:

validate :validate_maximum_pending_actions_not_been_reached
def validate_maximum_pending_actions_not_been_reached
  errors[:base] << "maximum number of pending actions already reached" unless Action.where(status: 'pending').size <= 10
end

1 个答案:

答案 0 :(得分:5)

你的规范应该是这样的一个块。另外,您还可以使用错误类

指定错误
  it 'does not save the 11th action' do
    expect{ action.save! }.to raise_error(ActiveRecord::RecordInvalid) #(ActiveRecord::RecordInvalid,'Validation failed: maximum number of pending actions already reached')
  end