factory_girl与rspec2玩得不好 - ActiveRecord :: AssociationTypeMismatch

时间:2011-12-01 22:58:12

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

使用Rails 3.1.0rc8,Factory Girl 2.1.2,Factory Girl Rails 1.2.0和RSpec 2.7.0。

我认为我遇到的错误与this thread上讨论的问题有关。

我有一个看起来像这样的规范:

规格/集成/ my_integration_spec.rb

require 'spec_helper'

describe 'A Workflow' do
  before(:all) do
    @reseller = Factory(:reseller)
    @product = Factory(:product, :reseller => @reseller)
  end

  describe 'A feature' do
    it 'Does something' do
    end

    describe 'A sub-feature' do
      before(:all) do
        # Error!
        @product.sold_at << Factory(:outlet, :reseller => @reseller)
      end

      it 'Does something' do
      end
    end
  end

运行此规范会导致子功能中出现异常:

Failure/Error: @product.sold_at << Factory(:outlet, :reseller => @reseller)
ActiveRecord::AssociationTypeMismatch:
  Reseller(#90828680) expected, got Reseller(#59351220)

有趣的是,当我将嵌套的前挂钩的内容移动到主挂钩之前,这个错误确实

require 'spec_helper'

describe 'A Workflow' do
  before(:all) do
    @reseller = Factory(:reseller)
    @product = Factory(:product, :reseller => @reseller)

    # No error!
    @product.sold_at << Factory(:outlet, :reseller => @reseller)
  end

  describe 'A feature' do
    it 'Does something' do
    end

    describe 'A sub-feature' do
      it 'Does something' do
      end
    end
  end

非常感谢您理解这个问题。

1 个答案:

答案 0 :(得分:0)

每个spec文件中只能有一个before(:all)。在(:all)之前使用before(:all) at the top of a spec and then {:1}} in a describe block. This is the reason that your second example works, you have removed the second之前使用before(:all)

另外,请注意after(:all)。此处创建的任何数据都不会在规范末尾从数据库中删除,您需要在{{1}}中删除它或使用数据库清理器gem。有关推理,请参阅link