我正在创建工厂来替换我的灯具并生成测试数据。我已经安装了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
错误含义是什么?我做错了什么?
答案 0 :(得分:0)
错误含义是什么?我做错了什么?
您的工厂尝试使用与现有用户之一相同的电子邮件创建用户(难怪,看到电子邮件在工厂中是硬编码的)。您的数据库的唯一性约束抱怨。
您应该将序列用于用户电子邮件
# email "peter@example.com"
sequence(:email) { |n| "factory_#{n}@example.com" }
此工厂的第一位用户将收到电子邮件“factory_1@example.com”,第二位 - “factory_2@example.com”,依此类推。