2014-07-23 6 views
52

rspec을 사용하여 컨트롤러의 동작과 플래시 메시지 존재를 테스트하고 싶습니다.Rspec 3 플래시 메시지를 테스트하는 방법

행동 :

def create 
    user = Users::User.find_by_email(params[:email]) 
    if user 
    user.send_reset_password_instructions 
    flash[:success] = "Reset password instructions have been sent to #{user.email}." 
    else 
    flash[:alert] = "Can't find user with this email: #{params[:email]}" 
    end 

    redirect_to root_path 
end 

사양는 :

Failure/Error: expect(flash[:success]).to be_present 
    expected `nil.present?` to return true, got false 

답변

48

당신은 flash[:success]의 존재를 테스트 :

describe "#create" do 
    it "sends reset password instructions if user exists" do 
    post :create, email: "[email protected]"  
    expect(response).to redirect_to(root_path) 
    expect(flash[:success]).to be_present 
    end 
... 

하지만 오류가있어 그러나 당신의 c ontroller 사용중인 flash[:notice]

+0

아, 죄송합니다. 방금 전 미끄러졌습니다. 플래시 오류 [: notice] – MikeAndr

+2

이 경우 문제는 아마도 컨트롤러 코드 및/또는 테스트 데이터 때문일 수 있습니다. 'expect (flash [: notice])를'expect (flash [: alert])'로 변경해보십시오. 그러면 테스트가 통과하면 아마도 테스트 이메일이 존재하지 않는다는 것입니다. – rabusmar

32

플래시 메시지를 테스트하는 가장 좋은 방법은 shoulda 보석으로 제공됩니다. 당신이 플래시 메시지의 내용에 더 관심이 있다면

expect(controller).to set_flash 
expect(controller).to set_flash[:success] 
expect(controller).to set_flash[:alert].to(/are not valid/).now 
+0

신난다, 이것을 모르고 있었다! :) – Loed

14

이를 사용할 수 있습니다 :

expect(flash[:success]).to match(/Reset password instructions have been sent to .*/) 

또는

expect(flash[:alert]).to match(/Can't find user with this email: .*/) 

나는 것

은 다음 세 가지 예입니다 메시지가 중요하거나 자주 변경되지 않는 한 특정 메시지를 확인하는 것을 권장하지 마십시오.

0

다른 접근법은 컨트롤러에 플래시 메시지가 있고 대신 통합 테스트를 작성한다는 사실을 잊어 버리는 것입니다. 이렇게하면 JavaScript를 사용하거나 다른 방법으로 메시지를 표시하기로 결정한 후에 테스트를 변경할 필요가 없게됩니다. gem 'shoulda-matchers', '~> 3.1'

.nowset_flash에 직접 호출해야합니다

은으로도 https://stackoverflow.com/a/13897912/2987689

0

참조하십시오.

now 한정자와 함께 set_flash을 사용하고 다른 한정자 이후에 now을 지정하는 것은 더 이상 허용되지 않습니다.

set_flash 바로 뒤에 now을 사용하고 싶습니다. 예를 들면 다음과 같습니다.

# Valid 
should set_flash.now[:foo] 
should set_flash.now[:foo].to('bar') 

# Invalid 
should set_flash[:foo].now 
should set_flash[:foo].to('bar').now 
관련 문제