My 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
我制定了一个规范来测试这个:
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
测试失败,给我带来错误:
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)>'
这个问题的解决方案是什么?