Вопрос

When I run rake db:test:prepare,

It automagically generates my Factories :

require 'ffaker'

FactoryGirl.define do

  factory :user do
    sequence(:email) {|i| "marley_child#{i}@gmail.com" }
    password 'secret_shhh'
  end

  factory :brain do
    user FactoryGirl.create :user
  end

end

And then if I try to run rspec or even access my console with rails c test, I get a validation error :

/activerecord-3.2.6/lib/active_record/validations.rb:56:in `save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)

My Rspec :

  describe '#email' do
    context 'uniqueness' do
      let(:user) { FactoryGirl.build :user, email: 'Foo@Bar.COM' }
      subject { user.errors }
      before do
        FactoryGirl.create :user, email: 'foo@bar.com'
        user.valid?
      end
      its(:messages) { should include(email: ['has already been taken']) }
    end
  end

What makes no sense to me is I assumed this data was transactional. Why are my factories getting generated when I prepare by data and not within each test? What is the most appropriate way to do this?

Это было полезно?

Решение

Well, one problem is that in your :brain factory definition, you're actually calling FactoryGirl.create :user as part of the definition of the factory when you presumably meant to call it when the factory is invoked (i.e. user {FactoryGirl.create :user}).

As for why there is already a User in the database, I can't answer that except to say that sometimes even if you're running with transactions turned on and things go south, records can be left behind.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top