【问题标题】:factory_girl not playing nicely with rspec2 - ActiveRecord::AssociationTypeMismatchfactory_girl 不能很好地使用 rspec2 - ActiveRecord::AssociationTypeMismatch
【发布时间】:2011-12-01 22:58:12
【问题描述】:

我正在使用 Rails 3.1.0rc8、Factory Girl 2.1.2、Factory Girl Rails 1.2.0 和 RSpec 2.7.0。

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

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

spec/integration/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

非常感谢您对理解此问题的任何帮助。

【问题讨论】:

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


    【解决方案1】:

    每个规范文件中只能有一个before(:all)。使用before(:all) at the top of a spec and thenbefore(:each)in a describe block. This is the reason that your second example works, you have removed the secondbefore(:all)`。

    另外,请注意before(:all)。此处创建的任何数据都不会在规范结束时从数据库中删除,您需要在 after(:all) 中删除它或使用数据库清理器 gem。推理见link

    【讨论】:

    • 我认为您将每个规范文件限制为一个 before(:all) 是错误的。 RSpec2 (relishapp.com/rspec/rspec-core/docs/hooks/…) 的文档有一个嵌套 before(:each) 的示例,就像我在原始帖子中所做的那样。
    • 请重新检查您的原始帖子。您有两个 before(:all) 语句,没有 before(:each)。如果这是您拥有实际代码的方式,那么我认为它不会起作用。
    • 你能澄清一下“我认为它不会起作用”的意思吗?我创建了一个要点 (gist.github.com/1439749) 来演示嵌套 before(:all) 块的使用。据我所知,它工作正常。
    • 道歉 - 我已经回顾了我的理解,并且嵌套的 before(:all) 应该像你设置的那样工作。值得注意的是,不建议这样做 - 请参阅此 [David Chelimsky 回复的问题][ruby-forum.com/topic/584047]。我又看了你的代码 - 你能试试 `@product.sold_at @product, :reseller => @reseller)
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多