【问题标题】:Rails 4 - rspec test dont pass for Polymorphic AssociationRails 4 - 多态关联的 rspec 测试未通过
【发布时间】:2014-10-12 23:08:10
【问题描述】:

我试图测试一个多态关联。

我正在使用 RSpec 3.0.2 和 shoulda-matchers 2.6.2。我的 Rails 版本是:4.1.4 和 Ruby 2.1.2

我的第一个模型:app/models/address.rb

class Address < ActiveRecord::Base
    belongs_to :addressable, polymorphic: true
end

我的第二个模型:app/models/user.rb

class User < ActiveRecord::Base
    has_many :addresses, as: :addressable
end

我的第三个模型:app/models/company.rb

class Company < ActiveRecord::Base
     has_many :addresses, as: :addressable
end

对于地址表,我有这个迁移:

class CreateAddresses < ActiveRecord::Migration
    def change
        create_table :addresses do |t|
            t.string :description
            t.references :addressable, polymorphic: true
            t.timestamps
        end
    end
end

对于我的第一个规范,我有:spec/models/address_spec.rb

require 'rails_helper'

RSpec.describe Address, :type => :model do
    it { should belong_to :addressable }
end

但是当我尝试运行规范时,我遇到了这个错误:

失败:

1) 地址应属于可寻址 失败/错误:它 { 应该属于 :addressable } 期望地址有一个称为可寻址的belongs_to 关联(地址没有addressable_id 外键。) # ./spec/models/address_spec.rb:4:in `block (2 levels) in '

迁移生成的表:

你能帮我确定我失踪的地方吗?我只是从谷歌上看到了 stackoverflow,但没有解决方案。

【问题讨论】:

  • 不要发布文字图片,而是将实际文字直接复制并粘贴到您的帖子中。文本图像不易解析、搜索或访问。
  • 我明白了。发布更新谢谢@AndrewMarshall

标签: ruby-on-rails rspec


【解决方案1】:

addressable_id 列不在您的测试数据库中。运行:

bundle exec rake db:test:clone

将您的数据库更改同步到您的测试数据库。

【讨论】:

  • 谢谢..它有效...你拯救了我的一天。但是运行这个命令我得到这个警告:WARNING: db:test:clone is deprecated. The Rails test helper now maintains your test schema automatically, see the release notes for details.
  • @PSantos, stackoverflow.com/questions/23351783/… 将向您展示如何更新您的 spec_helper,以便 Rails 维护您的测试架构。
  • 嗨@infused,这无济于事,因为在我的规范/rails_helper.rb(由 rails g rspec:install 生成)中我只有这一行:ActiveRecord::Migration.maintain_test_schema! 但架构没有自动更新
  • @PSantos,您应该单独提出一个关于 ActiveRecord::Migration.maintain_test_schema! 不起作用的问题。
猜你喜欢
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
相关资源
最近更新 更多