2015-09-05 117 views
2

請幫助檢查重定向。我有控制器:RSpec測試重定向

def create 
    @poll = current_user.polls.build(poll_params) 

    if @poll.save  
    flash[:success] = 'Голосование создано' 
    redirect_to user_polls_path(current_user) 
    else 
    flash.now[:error] = 'Голосование не создано' 
    @user = User.find(params[:user_id]) 
    render 'new' 
    end 
end 

規格/請求/ polls_spec.rb:

require 'rails_helper' 

RSpec.describe "Polls", type: :request do 
    describe "return check" do 
    it "#create" do 
     @user = FactoryGirl.create(:user) 
     @poll = FactoryGirl.create(:poll, user: @user) 
     # binding.pry #@user OK, @poll OK 
     expect(@poll).to redirect_to(user_polls_path @user) 
    end    
    end 
end 

但在控制檯運行後,我得到folloew錯誤消息:

$ rspec spec/requests 
...F 
Failures: 
    1) Polls return 200 status code for GET /polls #create 
    Failure/Error: expect(@poll.save).to redirect_to(user_polls_path @user) 
    NoMethodError: 
     undefined method `response_code' for nil:NilClass 

回答

0

使用

expect(response).to redirect_to(user_polls_path @user) 

redirect_to做什麼es幕後操作是檢查expect中使用的對象的response_code屬性。

這就是爲什麼你會得到undefined method 'response_code' for nil:NilClass錯誤。