【问题标题】:How to create temporal table in rspec test如何在 rspec 测试中创建时态表
【发布时间】:2013-06-19 15:11:01
【问题描述】:

我有一个模型地址和一个可寻址模块,为包括此可寻址模块的 AR 类注入 *belongs_to :address* 关系。

我想测试包含这个模块的那个类有这个关系。

上课地址:

class Address < ActiveRecord::Base
  attr_accessible :street, :zip
end

模块可寻址

module Addressable
  def self.included(base)
    base.class_eval <<-CLASS_METHODS
          belongs_to :address
          validates :address, presence: true
    CLASS_METHODS
  end
end

测试代码:

require 'spec_helper'
describe 'Addressable' do

  subject do
    class OtherModel < ActiveRecord::Base
      include Addressable
    end
  end

  before(:all) do
    connection = ActiveRecord::Base.connection
    connection.create_table :othermodels do |t|
      t.references :address
    end
  end

  after(:all) do
    connection.drop_table :othermodels
  end

  it "should validate presence of address"do
    should validate_presence_of(:address)
  end

  it "should belongs to address" do
should belong_to :continent
  end
end

我的测试失败了

 1) Addressable should validate presence of address
   Failure/Error: should validate_presence_of(:address)
   NoMethodError:
     undefined method `address=' for OtherModel(Table doesn't exist):Class

我认为 before(:all) 没有起作用。如何创建此表。

【问题讨论】:

    标签: ruby-on-rails testing activerecord rspec


    【解决方案1】:

    您可以尝试在 OtherModel 定义中将表名显式设置为您的模型中存在的具有可寻址的表。

    table_name = "some table that exists with addressable columns"
    

    【讨论】:

      【解决方案2】:

      晚了四年,但我想测试类似的东西并找到了你的问题。我认为你做的一切都是对的,除了按照惯例,表应该被称为other_models(你的班级是OtherModel)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-10
        • 2014-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        相关资源
        最近更新 更多