2012-09-15 58 views
2

我的位置模型可以有網站。如果該位置在線,該網站只能在場。在保存之前,網站必須具有正確的格式。Rspec:如何在有效的情況下編寫條件驗證

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)>' 

這個問題的解決方案是什麼?

回答

2

您的spec文件寫得有點不對。 &&不符合您的期望。

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 
+0

好的,現在它已經過去了。謝謝。 – LearningRoR

相關問題