【问题标题】:rspec validation with unlessrspec验证,除非
【发布时间】:2013-04-04 18:42:58
【问题描述】:

brief.rb

# encoding: utf-8
class Brief < ActiveRecord::Base
  belongs_to :project  
  validates_numericality_of :duration, :only_integer => true, :less_than_or_equal_to => 15, :greater_than_or_equal_to => 5, :unless => Proc.new{ |b| b.project.project_type.express_project }
end

brief_spec.rb

require 'spec_helper'

describe Brief do

  before(:all) do
    @project =Factory(:project)
    @brief=Factory.build(:brief,:project => @project)
  end

  context 'non-specific tests' do

    subject { @brief }

    it { should belong_to(:project) }

    it { should validate_presence_of(:project}

  end
end

这些是我的简要模型和简要规格文件。但我不知道如何测试 除非部分的 validates_numericality_of。有人可以尝试过吗?

【问题讨论】:

    标签: ruby-on-rails shoulda specifications


    【解决方案1】:

    使用上下文并测试不同的条件

    例如

    context "when duration is more than 5 but less than 15" do 
      before do 
        subject.duration = 10
      end
      it { should validate_presence_of(:project) }
    end
    context "when duration is more than 15" do 
      before do 
        subject.duration = 20
      end
      it { should_not validate_presence_of(:project) }
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多