Reputation: 27192
My Location model which can have a website. The website only has to be present if the location is online. Before it is saved, the website must have the correct format.
location.rb
class Location < ActiveRecord::Base
attr_accessible :online :website
validates_presence_of :website, :if => 'online.present?'
validates_inclusion_of :online, :in => [true, false]
validate :website_has_correct_format, :if => 'website.present?'
private
def website_has_correct_format
unless self.website.blank?
unless self.website.downcase.start_with?('https://', 'http://')
errors.add(:website, 'The website must be in its full format.)
end
end
end
end
I make a spec to test for this:
location_spec.rb
require 'spec_helper'
describe Location do
before(:each) do
@location = FactoryGirl.build(:location)
end
subject { @location }
describe 'when website is not present but store is online' do
before { @location.website = '' && @location.online = true }
it { should_not be_valid }
end
end
The test fails, bringing to me the error:
Failures:
1) Location when website is not present but store is online
Failure/Error: it { should_not be_valid }
NoMethodError:
undefined method `downcase' for true:TrueClass
#./app/models/location.rb:82:in `website_has_correct_format'
#./spec/models/location_spec.rb:72:in `block (3 levels) in <top (required)>'
What is the solution to this problem?
Upvotes: 2
Views: 1858
Reputation: 3376
Your spec file is written a little bit wrong. The &&
is not working the way you expect it to.
require 'spec_helper'
describe Location do
before(:each) do
@location = FactoryGirl.build(:location)
end
subject { @location }
describe 'when website is not present but store is online' do
before do
@location.website = ''
@location.online = true
end
it { should_not be_valid }
end
end
Upvotes: 2