Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RSpec会话控制器-具有无效参数但没有设备的用户_Ruby On Rails_Ruby_Rspec_Rspec Rails - Fatal编程技术网

Ruby on rails RSpec会话控制器-具有无效参数但没有设备的用户

Ruby on rails RSpec会话控制器-具有无效参数但没有设备的用户,ruby-on-rails,ruby,rspec,rspec-rails,Ruby On Rails,Ruby,Rspec,Rspec Rails,我有一个简单的消息应用程序来学习RSpec,其中一个用户可以向另一个用户创建消息(只有登录的用户才能编写消息)。我没有使用Desive或FactoryBot,这个应用程序尽可能简单,只用于rspec学习 我想为sessions controller运行这些测试,但第二个测试(当用户有无效参数时)给了我一个错误预期响应为a,但是a,我不明白为什么,因为几个小时后 RSpec.describe SessionsController, type: :controller do let(:creat

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

我想为sessions controller运行这些测试,但第二个测试(当用户有无效参数时)给了我一个错误
预期响应为a,但是a,我不明白为什么,因为几个小时后

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
class sessioncontroller

我不太确定行
expect(赋值(:user))。不是eq-create\u-user
符合惯例,但这与结果无关。

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

expect(response).to redirect_to(action: 'new')
在控制器中,您只需渲染
new
模板:

render 'new'
我认为这是一个很好的方法来呈现新的
,你应该改变你的规范来预期这一点

expect(response).to render_template(:new)

你说得对,很完美(我浪费了很多时间)。我只是想知道,这是块之前使用的正确方式吗?我的意思是,这样做更优雅吗?文本示例更简洁(但可能更难理解),如果在同一上下文中有更多示例,它有助于避免重复相同的代码,