2

ウェブサイトを持つことができる My Location モデル。場所がオンラインである場合にのみ、Web サイトが存在する必要があります。保存する前に、Web サイトは正しい形式である必要があります。

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

この問題の解決策は何ですか?

4

1 に答える 1

2

あなたの仕様ファイルは少し間違って書かれています。が期待どおりに機能してい&&ません。

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
于 2012-09-15T00:56:40.743 に答える