开发者

factory_girls sequence and uniqueness

I have this setup in the factories开发者_如何学编程.rb.

Factory.sequence(:email) { |n| "email#{n}@factory.com" }
Factory.sequence(:username) { |n| "username_#{n}" }

Factory.define :user do |u|
  u.email { Factory.next :email }
  u.username { Factory.next :username }
  u.first_name 'Ivan'
  u.last_name 'Pupkin'
  u.latitude '42'
  u.longitude '-71'
  u.password 'qwerty'
  u.password_confirmation 'qwerty'
end

When i creating two instances of the Factory(:users) i got uniqueness error.

describe CartsController do

  let(:user) { Factory(:user) }
  let(:another_user) { Factory(:user) }
  let(:cart) { Factory(:cart) }


  describe 'show my cart' do
    before { sign_in user}
    before { get :show, :id => user.carts.last }
    it { should respond_with :success }
  end

  describe 'show different person cart' do
    before { sign_in user }
    before { get :show, :id => another_user.carts.last}
    it { should respond_with :redirect }
  end
end

Where is my problem?

Failure/Error: let(:user) { Factory(:user) }
Validation failed: Username has already been taken, Email has already been taken


It seems that there are records in your DB because fails let(:user) { Factory(:user) } and not let(:another_user) { Factory(:user) } so I see two possible solutions: add User.delete_all in the top or manually clean DB


Yeah, it's leftovers in the test db. You should have the following line in spec_helper.rb:

  config.use_transactional_fixtures = true

Note that this is useful even though you are using factories rather than fixtures. It wraps each example in a database transaction so that you have a clean slate every time. If you aren't using ActiveRecord, or if transactions are not going to work for you for any other reason, you need to pull in something like the database_cleaner gem to clean up the test database after each test run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜