gpt4 book ai didi

ruby-on-rails - FactoryGirl 的唯一性验证失败

转载 作者:行者123 更新时间:2023-12-04 05:49:09 25 4
gpt4 key购买 nike

我在使用 FactoryGirl 时遇到问题,我正在使用序列来避免重复字段,但无论如何验证都失败了。

输出:

  1) CustomersController anonymous user GET #edit is redirected to signin when accessing edit form
Failure/Error: get :edit, id: create(:customer)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/controllers/customers_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'

3) Customer public class methods executes its methods correctly #find_by_id_or_name finds customer by name
Failure/Error: let(:john) {create(:customer, name: 'John Doe X')}
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/models/customer_spec.rb:25:in `block (3 levels) in <top (required)>'
# ./spec/models/customer_spec.rb:38:in `block (5 levels) in <top (required)>'
# -e:1:in `<main>'

工厂:
FactoryGirl.define do
factory :customer do
user
name {Faker::Name.name}
sequence(:mail) { |n| "person#{n}@example.com" }
address {Faker::Address.street_address}
phone {Faker::PhoneNumber.phone_number}
end
end

FactoryGirl.define do
factory :user do
sequence(:email) {|i| "example#{i}@example.com"}
password {Faker::Internet.password(10)}
end
end

这些是失败的测试:
RSpec.describe Customer, type: :model do
describe "public class methods" do
let(:john) {create(:customer, name: 'John Doe X')}
let(:frank) {create(:customer)}


context "responds to its methods" do
it "responds to #find_by_id_or_name" do
expect(Customer).to respond_to(:find_by_id_or_name)
end
end

context "executes its methods correctly" do
context "#find_by_id_or_name" do
it "finds customer by name" do
customer = Customer.find_by_id_or_name('John Doe X')
expect(customer).to eq john
end
it "finds customer by id" do
customer = Customer.find_by_id_or_name(frank.id)
expect(customer).to eq frank
end
end
end
end
end



RSpec.describe CustomersController, type: :controller do
context "signed in user" do
before :each do
@user = create(:user)
end
describe "GET #edit" do
it "renders :edit view" do
get :edit, id: create(:customer).id
expect(response).to render_template(:edit)
end
end

describe "DELETE #destroy" do
before :each do
@customer = create(:customer, user: @user)
end
it "deletes record" do
expect {delete :destroy, id: @customer.id}.to change(Customer, :count).by(-1)
end
end
end
end

这在我的应用程序中发生在我身上。我只是复制了一些适用于客户的测试。

谢谢

最佳答案

我的问题与没有适当配置 database_cleaner 有关。本帖中的配置解决了问题:How can I clean my database between erroneous rspec specs?

关于ruby-on-rails - FactoryGirl 的唯一性验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31094675/

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