水豚和工厂女孩"Email has already been taken"错误



我认为这可能与我在这个问题中描述的问题有关。

我不明白为什么Capybara在使用Factory Girl创建用户Factory时无法在我的rails应用程序上测试注册表格。我一直收到一个email has already been taken错误。这是我的工厂:

FactoryGirl.define do
sequence :email do |n|
"email#{n}@example.com"
end
factory :user do
email
password "secret"
password_confirmation "secret"
end
end

这是我的注册测试:

require "test_helper"
describe "Signup integration" do
before(:each) do
visit signup_path
end
it "successfully routes to the signup page" do
page.text.must_include "Sign Up"
end
it "signs up a new user" do
user = FactoryGirl.create(:user)
fill_in "user_email", :with => user.email
fill_in "Password", :with => user.password
fill_in "Password confirmation", :with => user.password_confirmation
click_button "Create User"
current_path == "/"
page.text.must_include "Signed up!"
end  
end

这是我的test_helper.rb:

ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "minitest/autorun"
require "capybara/rails"
require "active_support/testing/setup_and_teardown"
class IntegrationTest < MiniTest::Spec
include Rails.application.routes.url_helpers
include Capybara::DSL
register_spec_type(/integration$/, self)
def last_email
ActionMailer::Base.deliveries.last
end
def reset_email
ActionMailer::Base.deliveries = []
end
end
class HelperTest < MiniTest::Spec
include ActiveSupport::Testing::SetupAndTeardown
include ActionView::TestCase::Behavior
register_spec_type(/Helper$/, self)
end
Turn.config.format = :outline

我真的不确定那会出什么问题。如果我将Capybarasave_and_open_page方法添加到每一行,它可以一直到密码字段,但Capybara无法填写密码字段。它会在电子邮件字段中添加一个唯一的电子邮件地址,如email3@example.com,但无法添加Factory Girl密码。如果我在测试中输入一个纯文本密码(fill_in "Password", :with => "password")),它就可以填写字段,但这似乎不是测试的正确方法

我也不确定这是否也与我在应用程序中的登录测试有关?问题可能是Capybara在登录测试中以另一个用户身份登录吗?如果是这样的话,你如何清理你的测试?

最后,这里是我的gemfile,以防相关:

source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'jquery-rails'
gem 'pg'
gem 'heroku'
gem 'taps'
gem 'sorcery'
gem 'bootstrap-sass'
gem 'simple_form'
group :assets do
gem 'sass-rails',   '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
group :test do
gem 'minitest'
gem 'capybara'
gem 'capybara_minitest_spec'
gem 'turn'
gem 'factory_girl_rails'
end

问题可能在这一行

user = FactoryGirl.create(:user)

尝试将其更改为

user = FactoryGirl.build(:user)

FactoryGirl.create创建User对象的一个实例并将其保存到数据库中。build创建一个实例,但不将其保存到DB中。

数据库清理程序帮助了我..

gemfile

gem 'database_cleaner'

minitest_help.rb

class MiniTest::Spec
include FactoryGirl::Syntax::Methods
before :each do
DatabaseCleaner.clean
end
end

之所以会发生这种情况,是因为您对电子邮件列使用了相同的值,该列应该是唯一的

在Gemfile的group :development, test中使用gem fakegem database_cleaner

Fakers允许您为记录生成随机值,而database_cleaner在创建记录后清理数据库

相关内容

最新更新