2017-01-20 1 views
1

이 코드를 테스트 해 보았습니다. 내 레일 애플 리케이션의 내부에있는 application_helper.RSpec 3.5로이 코드를 테스트하는 방법은 무엇입니까?

def greet 
    now = Time.now 
    today = Date.today.to_time 

    morning = today.beginning_of_day 
    noon = today.noon 
    evening = today.change(hour: 17) 
    night = today.change(hour: 20) 
    tomorrow = today.tomorrow 

    if (morning..noon).cover? now 
    'Good Morning' 
    elsif (noon..evening).cover? now 
    'Good Afternoon' 
    elsif (evening..night).cover? now 
    'Good Evening' 
    end 
end 

답변

1

Timecop 보석을 사용하여 시간 기반 코드를 테스트하는 것이 좋습니다. 테스트 도우미에 대한 일반적인 내용은 RSpec documentation을 참조하십시오.

당신이 뭔가를 작성할 수

RSpec.describe ApplicationHelper, type: :helper do 
    describe '#greet' do 
    subject { helper.greet } 

    context 'in the morning' do 
     around do |example| 
     Timecop.travel(Time.now.change(hour: 2), &example) 
     end 

     it { is_expected.to eq('Good Morning') } 
    end 
    end 
end 

여기에서 일어나고있는 것은 around 블록 (즉, 특정 시간을 시뮬레이션) '시간을 거슬러'의 예와 수익을 실행 타임 캅를 호출하는 것입니다 그 후에는 정기적 인 행동으로 되돌아갑니다. Timecop을 사용할 때는 원래 시간으로 돌아 오는 것을 잊지 말아야하므로 around 블록을 사용하는 것이 좋습니다.

관련 문제