验证URL(如果存在),但允许它为空

时间:2014-01-27 04:43:31

标签: ruby-on-rails validation rspec model ruby-on-rails-4

我在地点模型中有一个:box_office_url。我希望模型在以下情况下有效:

  • :box_office_url为空白
  • 或者:box_office_url存在且有效的网址

我使用rspec编写了以下测试:

require 'spec_helper'

describe Location do 

  let(:location) { FactoryGirl.create(:location) }

  subject { location }

  describe ":box_office_url" do

    context "if :box_office_url is blank" do
      before do
        location.box_office_url = nil
      end
      it { should be_valid }
    end

    context "if :box_office_url does not have URL" do
      before do
        location.box_office_url = "this is not a url"
      end
      it { should_not be_valid }
    end

    context "if :box_office_url contains a valid URL" do
      before do
        location.box_office_url = "http://thetheater.com/index.php"
      end
      it { should be_valid }
    end
  end
end

到目前为止,这是模型:

class Location < ActiveRecord::Base
  validates_format_of :box_office_url, :with => URI::regexp(%w(http https))
end

测试中:box_office_url不是空白传递。但是列空白的测试失败了。

Failures:

  1) Location :box_office_url if :box_office_url is blank 
     Failure/Error: it { should be_valid }
       expected #<Location id: 1, name: "One Great Theater", box_office_url: nil, created_at: "2014-01-27 04:41:06", updated_at: "2014-01-27 04:41:06", description: "An intimate modern theater with 99 seats.", street_address: "1234 Main Street", street_address_2: nil, city: "Chicago", state: "IL", zip: "61550", box_office_phone: "312-234-9999", website_url: "http://thetheater.com", map_url: "https://goo.gl/maps/iSZCP", embedded_map_code: "<iframe src=\"https://www.google.com/maps/embed?pb=!..."> to be valid, but got errors: Box office url is invalid
     # ./spec/models/location_spec.rb:40:in `block (4 levels) in <top (required)>'

任何人都可以告诉我在模型中放置什么,以便模型仍然有效,空白吗?