我有一个简单的消息应用程序,用于学习RSpec,其中一个用户可以向另一个用户创建消息(只有登录的用户才能编写消息)。我没有使用devise登录或注册用户,此应用程序对于rspec学习来说尽可能简单。
我想在会话控制器中测试创建方法:
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
def logged_in_redirect
if logged_in?
flash[:error] = 'You are already logged in'
redirect_to root_path
end
end
这是我的会话控制器规范中的相关代码:
RSpec.describe SessionsController, type: :controller do
describe 'POST #create' do
context 'when password is correct' do
let(:user) { User.create(username: 'John', password: 'test123') }
it 'redirect to root path' do
post :create, session: { username: 'John', password: 'test123' }
expect(response).to have_http_status(:redirect)
end
end
end
end
错误指出nil:NilClass的未定义方法“ []”。它可以在应用程序中按预期方式工作。我想念什么?我应该在session[:user_id]
之后使用let(:user)
吗?
答案 0 :(得分:1)
使用let定义记忆的辅助方法。该值将被缓存 跨同一示例中的多个调用,但不跨示例。 请注意,let是惰性求值的:直到第一次调用它定义的方法时,才进行求值。您可以使用let!至 强迫 -列表项
每个示例之前方法的调用。 xou可以参考此内容以获取更多详细信息relish docs
可能性1
RSpec.describe SessionsController, type: :controller do
describe 'POST #create' do
before :each do
@user = User.create(username: 'John', password: 'test123')
end
context 'when password is correct' do
it 'redirect to root path' do
post :create, params: {session: { username: @user.username, password: @user.password }}
expect(response).to have_http_status(:redirect)
end
end
end
end
可能性2
RSpec.describe SessionsController, type: :controller do
let(:create_user) do
@user = User.create(username: 'John', password: 'test123')
end
describe 'POST #create' do
context 'when password is correct' do
it 'redirect to root path' do
create_user
post :create, params: {session: { username: @user.username, password: @user.password }}
expect(response).to have_http_status(:redirect)
end
end
end
end