0

我正在按照文档中的说明进行操作,但仍然出现验证错误:

验证失败:电子邮件已被占用

FactoryGirl.define do
  sequence :email do |n|
    "test#{n}@factory.com"
  end

  factory :user do
    email           
    password              '12345678'
    password_confirmation '12345678'
    goal_id               1
    experience_level_id   1
    gender                'Female'
  end
end

有人知道我在这里做错了什么吗?

编辑:

这是失败的规范。如果您取消注释主题块并注释掉 FactoryGirl 内容,它工作正常。我正在尝试改用 FactoryGirl。

require 'spec_helper'
require 'cancan/matchers'

describe User do
  # subject(:user) do
  #   Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1')
  #   User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female')
  # end
  FactoryGirl.create(:program)
  puts FactoryGirl.create(:user).inspect

  it "should be assigned a program when it's created" do
    user.programs.should exist
  end

  it "should be valid with a name, goal, password, password_confirmation, experience_level, and gender" do
    user.should be_valid
  end

  it { should respond_to(:programs) }
  its('programs.last.name') {should == 'Test'}

  it "should be assigned imperial as the default measurement_units" do
    user.measurement_units.should eq("imperial") 
  end

  it 'validates presence of gender, goal_id, and experience_level_id' do
    user = User.new(gender: nil)
    user.should validate_presence_of(:gender)
    user.should validate_presence_of(:goal_id)
    user.should validate_presence_of(:experience_level_id)
  end
end

编辑2:

我已经按照答案之一的建议更新了我的规范,所以现在我的规范运行了,但是我得到一个失败的测试并出现验证错误。这是更新的代码:

describe User do
  subject(:user) do
  #   Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1')
  #   User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female')
    FactoryGirl.create(:program)
    FactoryGirl.create(:user)
  end

  it "should be assigned a program when it's created" do
    user.programs.should exist
  end

来自失败测试的消息:

Failures:

  1) User should be assigned a program when it's created
     Failure/Error: FactoryGirl.create(:user)
     ActiveRecord::RecordInvalid:
       Validation failed: Email has already been taken
     # ./spec/models/user_spec.rb:9:in `block (2 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:13:in `block (2 levels) in <top (required)>'

有任何想法吗?

4

2 回答 2

2

您不能只在这样的测试类中间创建工厂实例。FactoryGirl 替代了您之前在代码中的实例化 - 离开subject块,只需将两create行替换为 FactoryGirl 调用。

(更好的是,它们应该是let块而不是subject块,但那是另一回事)

如果你不是在 Rspec 知道的上下文中做事,它就无法事后清理。

于 2013-10-08T01:36:36.730 回答
0

你的 Gemfile 中有什么?使用这个我有更好的成功

  gem 'factory_girl_rails', :group => :test

而不是在“组:开发,:测试做”部分中列出它。

于 2013-10-08T01:30:45.443 回答