Capybara和Factory Girl的“电子邮件已被采取”错误

时间:2012-11-18 17:37:26

标签: ruby-on-rails ruby-on-rails-3 testing capybara factory-bot

我认为这可能与issues I described in this question

有关

我无法弄清楚为什么Capybara在使用Factory Girl创建用户工厂时无法在我的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

我不确定那可能有什么问题。如果我将Capybara save_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

3 个答案:

答案 0 :(得分:3)

问题可能出在这一行

user = FactoryGirl.create(:user)

尝试将其更改为

user = FactoryGirl.build(:user)

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

答案 1 :(得分:1)

数据库清洁工帮助了我..

的Gemfile

  gem 'database_cleaner'

minitest_helper.rb

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

答案 2 :(得分:0)

这种情况正在发生,因为您使用的电子邮件列的值应该是唯一的

在Gemfile的gem fake中使用gem database_cleanergroup :development, test

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