RSpec测试重定向

时间:2015-09-05 14:12:00

标签: ruby-on-rails 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

但在控制台中运行后,我得到了以下错误消息:

$ 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

1 个答案:

答案 0 :(得分:0)

使用

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

幕后的redirect_to是检查response_code中使用的对象的expect属性。

这就是您收到undefined method 'response_code' for nil:NilClass错误的原因。