可安装在轨道上的测试夹具中的关联

时间:2011-11-22 15:42:58

标签: activerecord ruby-on-rails-3.1

我在新的可安装新发动机的单元测试中遇到了问题。

我有两个基本模型:

module Ads
  class Category < ActiveRecord::Base
    set_table_name :categories
    has_many :ads
  end
end

module Ads
  class Ad < ActiveRecord::Base
    set_table_name :ads
    belongs_to :category
  end
end

它在rails控制台中运行得非常好。

ruby-1.9.2-p290 :007 > c = Ads::Category.create(title: 'foo')
(0.4ms)  BEGIN
SQL (1.0ms)  INSERT INTO "categories" ("created_at", "title", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["created_at", Tue, 22 Nov 2011 15:34:41 UTC +00:00], ["title", "foo"], ["updated_at", Tue, 22 Nov 2011 15:34:41 UTC +00:00]]
(18.0ms)  COMMIT
=> #<Ads::Category id: 2, title: "foo", created_at: "2011-11-22 15:34:41", updated_at: "2011-11-22 15:34:41"> 
ruby-1.9.2-p290 :008 > c.ads.create(title: 'bar')
(0.6ms)  BEGIN
SQL (1.1ms)  INSERT INTO "ads" ("category_id", "created_at", "title", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["category_id", 2], ["created_at", Tue, 22 Nov 2011 15:34:43 UTC +00:00], ["title", "bar"], ["updated_at", Tue, 22 Nov 2011 15:34:43 UTC +00:00]]
(16.8ms)  COMMIT
=> #<Ads::Ad id: 2, title: "bar", category_id: 2, created_at: "2011-11-22 15:34:43", updated_at: "2011-11-22 15:34:43"> 

我接受了单元测试:

# test/unit/ads/category_test.rb
require 'test_helper'

module Ads
  class CategoryTest < ActiveSupport::TestCase
    # by default it searches in dummy app, is there any cleaner way to change this?
    self.fixture_path = Rails.root.parent + "./fixtures/ads" 
    fixtures :categories, :ads

    test "should find cars" do
      assert_equal 1, Category.where(title: 'Cars').count
    end
  end
end

# test/fixtures/ads/categories.yml
cars:
  title: Cars

# test/fixtures/ads/ads.yml
foo:
  title: Foo
  category: cars

当我运行单元测试时:

rake app:test:units

在填充测试db:

期间最终会出错
ActiveRecord::StatementInvalid: PGError: ERROR:  column "category" of relation "ads" does not exist
LINE 1: INSERT INTO "ads" ("title", "category") VALUES ('Foo', 'cars...

似乎广告&lt; - &gt;类别关联'被忽略。 相同的方法在独立的rails应用程序中完美运行。 我的问题是:我做错了什么? 另一个问题是,是否有更清洁的解决方案来改变灯具路径?

Rails:3.1.3

1 个答案:

答案 0 :(得分:0)

我有完全相同的问题,但使用Rails 3.0引擎。我无法正确修复它,但作为一种解决方法,我做到了这一点。

而不是:

category: cars

执行:

category_id: <%= Fixtures.identify(:cars) %> 

这很有效,因为ID实际上是标签的哈希值。而Fixtures.identify就是那种哈希。