RSpec会话控制器-具有无效参数的用户,没有设计

时间:2018-12-10 22:54:55

标签: ruby-on-rails ruby rspec rspec-rails

我有一个简单的消息应用程序,用于学习RSpec,其中一个用户可以向另一个用户创建消息(只有登录的用户才能编写消息)。我没有使用过devise或FactoryBot,这个应用程序对于rspec学习来说尽可能简单。

我想为会话控制器运行这些测试,但是第二个(当用户具有无效的参数时)给我一个错误Expected response to be a <3XX: redirect>, but was a <200: OK>,而且我不明白为什么要花几个小时。

RSpec.describe SessionsController, type: :controller do
  let(:create_user) { @user = User.create(username: 'John', password: 'test123') }

  describe 'POST #create' do

    context 'when user is logged in' do
      it 'loads correct user details and redirect to the root path' do
        create_user
        post :create, params: { session: { username: @user.username, password: @user.password } }
        expect(response).to redirect_to(root_path)
      end
    end

    context 'when user has invalid params' do
      before do
        create_user
        post :create, params: { session: { username: @user.username, password: 'somepass' } }
      end

      it 'render new action' do
        expect(assigns(:user)).not_to eq create_user
        expect(response).to redirect_to(action: 'new')
      end
    end
  end
end

会话控制器

class SessionsController < ApplicationController
  before_action :logged_in_redirect, only: %i[new create]

  def new; end

  def create
    user = User.find_by(username: params[:session][:username])
    if user && user.authenticate(params[:session][:password])
      session[:user_id] = user.id
      flash[:success] = 'You have successfully logged in'
      redirect_to root_path
    else
      flash.now[:error] = 'There was something wrong with your login'
      render 'new'
    end
  end
end

我不确定expect(assigns(:user)).not_to eq create_user行是否符合约定,但这与结果无关紧要。

1 个答案:

答案 0 :(得分:1)

在测试中,您期望重定向响应:

expect(response).to redirect_to(action: 'new')

在控制器中,您只需渲染new模板:

render 'new'

我认为这是渲染new的好方法,您应该更改规格以达到预期效果。

expect(response).to render_template(:new)