Reputation: 2227
I have a :box_office_url in a model for Locations. I'd like the model to be valid if:
I've written the following tests using 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
And here is the model so far:
class Location < ActiveRecord::Base
validates_format_of :box_office_url, :with => URI::regexp(%w(http https))
end
The tests in which :box_office_url are not blank pass. But the test with the column blank fails.
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)>'
Can anyone show me what to put in the model so that the model is still valid with a blank?
Upvotes: 0
Views: 1049
Reputation: 20614
Use the allow_blank option
http://guides.rubyonrails.org/active_record_validations.html#allow-blank
Or an unless with proc
http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
Upvotes: 1