Rspec增加了额外的默认错误

时间:2013-12-13 07:13:13

标签: ruby-on-rails rspec model

我有以下型号:

class Court < ActiveRecord::Base
#Relationships
#belongs_to :case, class_name: 'Case', foreign_key: 'case_id'
belongs_to :user, class_name: 'User', foreign_key: 'user_id'
#Scopes


#Attributes
attr_accessible :court_name, :court_notes, :street, :city, :state, :zip

#Validations
validates_lengths_from_database
validates :court_name, presence: true, length: { in: 3..200 }
validates :court_notes, length: { maximum: 250 }
validates :court_notes, :street, :city, :state, :zip, presence: true
validates :street, :city, :state, length: { maximum: 30, message: 'max length allowed is 30' }
validates :zip, numericality: true, length: { is: 5, message: 'length should be 5' }, allow_blank: true
#Callbacks


#Methods

以下spec文件:     需要'spec_helper'

describe Court do

context '#object' do
  it 'has a valid factory' do
    FactoryGirl.build(:court).should be_valid
  end
end

context '#associations' do
  it { should belong_to(:user) }
end

context '#values' do
  it { should respond_to(:court_name) }
  it { should respond_to(:court_notes) }
  it { should respond_to(:street) }
  it { should respond_to(:city) }
  it { should respond_to(:state) }
  it { should respond_to(:zip) }
end

context '#protected' do
  it { should_not allow_mass_assignment_of(:id) }
  it { should_not allow_mass_assignment_of(:case_id) }
end

context '#validations' do
  it { should validate_presence_of(:court_name) }
  it { should ensure_length_of(:court_name).is_at_most(200) }
  it { should ensure_length_of(:court_notes).is_at_most(250) }
  it { should ensure_length_of(:street).is_at_most(30) }
  it { should ensure_length_of(:city).is_at_most(30) }
  it { should ensure_length_of(:state).is_at_most(30) }
end
end

当我运行规范时,我收到错误

1) Court#validations 
 Failure/Error: it { should ensure_length_of(:city).is_at_most(30) }
   Did not expect errors to include "is too long (maximum is 30 characters)" when city is set to "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", got error: 
 # ./spec/models/court_spec.rb:52:in `block (3 levels) in <top (required)>'

以及城市和州的其他两个类似错误。从哪里添加额外的错误消息?据我所知,验证仅在一个地方发生,但是产生了两个错误消息。

1 个答案:

答案 0 :(得分:0)

原因是您的自定义消息:

message: 'max length allowed is 30'

Shoulda希望您有确切的错误消息作为默认消息:

'is too long (maximum is 30 characters)'

但是你有不同的信息,所以期望失败。您可以查看Shoula doc以了解如何允许自定义消息。