加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在一个gem中测试ActiveRecord模型?

发布时间:2020-12-16 20:04:04 所属栏目:百科 来源:网络整理
导读:我试图从Rails 3.2.3应用程序中提取一组模型到一个gem,以便它们可以用作应用程序之间的共享接口. 我将模型移动到一个模块中,并将其放在lib / invite_interface / invite.rb中 module InviteInterface class Invite ActiveRecord::Base belongs_to :user end
我试图从Rails 3.2.3应用程序中提取一组模型到一个gem,以便它们可以用作应用程序之间的共享接口.

我将模型移动到一个模块中,并将其放在lib / invite_interface / invite.rb中

module InviteInterface
  class Invite < ActiveRecord::Base
    belongs_to :user
  end

  def to_json; end;
  def from_json; end;
end

我将rspec放入gemfile,成功运行,创建了以下规范:

require 'spec_helper'

describe InviteInterface::EncounterSurvey do
  it 'should belong to user' do
    subject.should respond_to(:user)
  end

end

不幸的是,我无法在模型上执行rspec,因为活动记录/ rspec需要一个活动的连接.

1) InviteInterface::Invite should belong to encounter survey set
   Failure/Error: subject.should respond_to(:user)
   ActiveRecord::ConnectionNotEstablished:
     ActiveRecord::ConnectionNotEstablished
   # /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in `retrieve_connection'
   # /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:168:in `retrieve_connection'
   # /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:142:in `connection'
   # /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/model_schema.rb:228:in `columns'
   # /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/model_schema.rb:243:in `column_defaults'

如何防止ActiveRecord查找数据库连接?

解决方法

您需要使用数据库测试您的库,因此您可以使用内存中的SQLite数据库进行测试.只需将其添加到spec_helper.rb中即可:
ActiveRecord::Base.establish_connection(:adapter => "sqlite3",:database => ":memory:")

并按如下所示创建您的模式:

ActiveRecord::Schema.define do
  self.verbose = false

  create_table :invites,:force => true do |t|
    t.string :text
  end
  ...
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读