如何在 rspec 测试中创建时态表

mon*_*lls 5 testing activerecord rspec ruby-on-rails

我有一个模型 Address 和一个模块 Addressable,为包含此模块 Addressable 的 AR 类注入 *belongs_to :address* 关系。

我想测试包含此模块的类是否具有这种关系。

班级地址:

class Address < ActiveRecord::Base
  attr_accessible :street, :zip
end
Run Code Online (Sandbox Code Playgroud)

模块可寻址

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

测试代码:

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
Run Code Online (Sandbox Code Playgroud)

我的测试失败了

 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
Run Code Online (Sandbox Code Playgroud)

我认为 before(:all) 没有发挥作用。我怎样才能创建这个表。

Bil*_*per 0

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

table_name = "some table that exists with addressable columns"
Run Code Online (Sandbox Code Playgroud)