1

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

我不明白为什么 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

我不太确定这有什么问题。如果我将 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
4

3 回答 3

3

问题可能出在这一行

user = FactoryGirl.create(:user)

尝试将其更改为

user = FactoryGirl.build(:user)

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

于 2012-11-18T17:46:51.627 回答
1

数据库清理器帮助了我..

宝石文件

  gem 'database_cleaner'

minitest_helper.rb

  class MiniTest::Spec
    include FactoryGirl::Syntax::Methods
    before :each do
      DatabaseCleaner.clean
    end
  end
于 2012-12-23T03:28:40.183 回答
0

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

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

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

于 2016-10-09T17:40:41.463 回答