【问题标题】:Testing validates length using ensure_length_of shoulda matchers测试使用 ensure_length_of shoulda 匹配器验证长度
【发布时间】:2013-06-20 12:12:56
【问题描述】:

在我测试这个验证长度时遇到问题 shoulda_matchers ensure_length_of

型号

class Plant < ActiveRecord::Base
  validates :code, :length => { :in => 2..6 } 
end

Rspec

require 'spec_helper'
describe Plant do

 before { @plant = FactoryGirl.create(:plant) } 
  it { should ensure_length_of(:code).is_at_least(2).with_message("is too short (minimum is 2 characters)")}
end

错误:

Failures:

  1) Plant
     Failure/Error: it { should ensure_length_of(:code).is_at_least(2).with_message("is too short (minimum is 2 characters)")}
       Did not expect errors to include "is too short (minimum is 2 characters)" when naics_code is set to "xx", got error: is too short (minimum is 2 characters)
     # ./spec/models/plant_spec.rb:11:in `block (2 levels) in <top (required)>'

谢谢!

【问题讨论】:

  • 我认为消息应该用 // 而不是引号括起来。它必须是一个正则表达式。
  • @prasad.surase 我也尝试了正则表达式(/您的消息在这里/)。它没有工作
  • 在没有任何subject 语句的情况下,it 子句正在运行 Plant 的 new 实例,而不是 FactoryGirl 实例。这会给shoulda 带来问题吗?此外,虽然我认为这不是一个因素,但文档建议您应该使用 with_too_short_message 而不是 with_message

标签: ruby ruby-on-rails-3 rspec shoulda


【解决方案1】:

正如@Peter Alfvin 所提到的,问题在于问题。 Rspec 实现应该如下所示:

require 'spec_helper'
describe Plant do

 before { @plant = FactoryGirl.create(:plant) }
  subject { @plant } 
  it { should ensure_length_of(:code).is_at_least(2).with_message("is too short (minimum is 2 characters)")}
end

【讨论】:

    猜你喜欢
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2015-01-18
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多