如何使用shoulda的消息测试mongoid模型验证?

时间:2013-03-22 11:15:13

标签: rspec mongoid shoulda

我有一个带有验证的模型,如下所示:

class Order
  include Mongoid::Document

  field :first_name, type: String
  field :last_name, type: String

  validates_presence_of :first_name, :message => "Can't be empty"
  validates_presence_of :last_name, :message => "Can't be empty"
end

我按rspecthoughtbot's shoulda描述模型:

describe Order do
  # validations
  it { should validate_presence_of(:first_name) }
  it { should presence_of(:last_name) }
end

但我失败了:

Failures:

  1) Order 
     Failure/Error: it { should validate_presence_of(:first_name) }
       Expected errors to include "can't be blank" when first_name is set to nil, got errors: ["first_name Can't be empty (nil)", "last_name Can't be empty (nil)"]
     # ./spec/models/order_spec.rb:10:in `block (2 levels) in <top (required)>'

此外,“应该”案例在模型验证中没有消息的情况下工作得很好。

如何使用消息测试模型验证?

1 个答案:

答案 0 :(得分:5)

mongoid-rspec gem允许使用消息测试模型验证。

it { should validate_uniqueness_of(:email).with_message("is already taken") }