2016-04-16 17 views
1

RubyとRspecから始めているので、あまり具体的でない場合は、あらかじめ不正な構文をお詫びします。別のクラスからメソッドを呼び出すruby

空港から天気のstormy?メソッドを呼び出すことができるように、空港と天気の2つのクラスがあります。私がしたいことは、天気が悪い時に飛行機が離陸するのを止めることです。 私はbad_weatherメソッドを定義しているが、それはここで 動作しませんが、私のコードです:RSpecの

describe Airport do 
    it ' does not allow planes to take off with stormy weather' do 
    subject.take_off double(:plane) 
    expect {(weather).to be_stormy?}.to raise_error "Flight cancelled due to bad weather" 
    end 
end 

私のテスト私は

class Weather 

    def stormy? 
    roll >= 6 
    end 

private 

    def roll 
    rand(10) 
    end 
end 

から方法を取りたいクラスそして、私はメソッドを呼び出すクラスを

class Airport 

    DEFAULT_CAPACITY = 10 

    def initialize 
    @planes = [] 
    @capacity = DEFAULT_CAPACITY 
    end 


    def take_off(plane) 
    fail "Flight cancelled due to bad weather" if bad_weather? 
    @planes.pop 
    end 

    def bad_weather? 
    weather = Weather.new 
    weather.stormy? 
    end 
end 

私は自分のRspecテストを知っていますが、どんな助けもありがたいです。

+0

代わりに何をしていますか? – 13aal

答えて

3

被験者が他のオブジェクトに依存しているこのような状況が発生した場合は、それらのオブジェクトを制御したいと考えています。あなたのシナリオでは、airportが知っているweatherを制御したいと考えています。

これを実行するには、stormy?と尋ねると、強制的にそれがtrueを返すようにする必要があります。そうすれば、Airportクラスを単体テストし、他のオブジェクトに対するすべての依存関係を確実にコントロールできます。ここで

は、私はこれを行うだろうかです:

class Airport 
    DEFAULT_CAPACITY = 10 

    def initialize 
    @planes = [] 
    @capacity = DEFAULT_CAPACITY 
    end 

    def take_off(plane) 
    fail "Flight cancelled due to bad weather" if bad_weather? 
    @planes.pop 
    end 

    def bad_weather? 
    weather.stormy? 
    end 

    def weather 
    @weather ||= Weather.new 
    end 
end 

そして、あなたのテストでは、あなたの空港でこれを行うことによって、持っているものweatherを制御しようとしている。

it 'does not allow planes to take off with stormy weather' do 
    my_airport = Airport.new 
    stormy_weather = Weather.new 
    allow(stormy_weather).to receive(:is_stormy?) { true } 
    allow(my_airport).to receive(:weather) { stormy_weather } 

    expect(my_airport.take_off("Boeing")).to raise_error "Flight cancelled due to bad weather" 
end 

@SteveTurczynの答えがありますまた有効です。空港の天気を暴風雨にするだけでなく、Weatherのインスタンスを作っているので、個人的には気に入らないのです。

0

これをテストする方法は、#stormy?を強制的にtrueにしてから、take_offメソッドの呼び出しによってエラーが発生するかどうかをテストすることです。

it 'does not allow planes to take off with stormy weather' do 
    allow_any_instance_of(Weather).to receive(:stormy?).and_return(true) 
    my_airport = Airport.new 
    expect(my_airport.take_off("Boeing")).to raise_error "Flight cancelled due to bad weather" 
end 

ちなみに、条件の逆数もテストしたいので、別のテストが便利です。

it 'does not complain about bad weather if weather is good' do 
    allow_any_instance_of(Weather).to receive(:stormy?).and_return(false) 
    my_airport = Airport.new 
    expect(my_airport.take_off("Boeing")).not_to raise_error "Flight cancelled due to bad weather" 
end 
関連する問題