gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:26:13 24 4
gpt4 key购买 nike

我正在尝试从 Rails 3.2.3 应用程序中提取一组模型到 gem 中,以便它们可以用作应用程序之间的共享接口(interface)。

我将模型移动到一个模块中并将其放入 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

关于ruby-on-rails - 在 gem 中测试 ActiveRecord 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10605053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com