gpt4 book ai didi

ruby - 加载 ./spec/controllers/users_controller_spec.rb 时出错

转载 作者:行者123 更新时间:2023-12-05 05:17:28 24 4
gpt4 key购买 nike

我正在创建工厂来替换我的固定装置并生成测试数据。我已经安装了 FactoryBot,但在运行“rspec”时出现错误。这是我得到的结果日志:

An error occurred while loading ./spec/controllers/users_controller_spec.rb.
Failure/Error: @user = FactoryBot.create(:user)

ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken
# ./spec/controllers/users_controller_spec.rb:5:in `block in <top (required)>'
# ./spec/controllers/users_controller_spec.rb:3:in `<top (required)>'


Finished in 0.00041 seconds (files took 38.38 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

这是我的 spec/factories/user_factory.rb

FactoryBot.define do
factory :user do
email "peter@example.com"
password "0123456"
first_name "Peter"
last_name "Example"
admin false
end
end

这是我的 spec/controllers/users_controller_spec.rb

require 'rails_helper'

describe UsersController, type: :controller do

@user = FactoryBot.create(:user)

# let (:user) { User.create!(email:"achochaocierva@gmail.com", password: "Ratadecierva2")}

describe 'GET #show' do
context 'when a user is logged in' do
before do
sign_in user
end
it 'loads correct user details' do
get :show, params: { id: user.id }
expect(response).to be_ok
expect(assigns(:user)).to eq user
end
end

context 'when a user is not logged in' do
it 'redirects to login' do
get :show, params: { id: user.id }
expect(response).to redirect_to(new_user_session_path)
end
end
end
end

错误的含义是什么?我做错了什么?

最佳答案

What would be the errors meaning? What am I doing wrong?

您的工厂尝试创建一个与现有用户具有相同电子邮件地址的用户(难怪,看到电子邮件地址在工厂中是硬编码的)。您的数据库的唯一性约束提示。

您应该为用户电子邮件使用序列

# email "peter@example.com"
sequence(:email) { |n| "factory_#{n}@example.com" }

来自该工厂的第一位用户将收到电子邮件“factory_1@example.com”,第二位 - “factory_2@example.com”,依此类推。

关于ruby - 加载 ./spec/controllers/users_controller_spec.rb 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com