FactoryGirl序列不起作用

时间:2013-10-07 23:49:54

标签: ruby-on-rails rspec factory-bot

我正在完成documentation中所说的内容,但仍然收到验证错误:

  

验证失败:已收到电子邮件

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)>'

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

(更好的是,它们应该let阻止而不是subject阻止,但这是一个不同的故事)

如果你没有在Rspec知道的情况下做事,那么事后就无法清理。

答案 1 :(得分:0)

你的Gemfile里有什么?我使用这个

取得了更大的成功
  gem 'factory_girl_rails', :group => :test

并未将其列在“group:development,:test do”部分。