【问题标题】:Isolation testing AR models?隔离测试 AR 模型?
【发布时间】:2011-11-20 09:00:26
【问题描述】:

我正在尝试重新构建模型规范以单独对其进行测试(将 ActiveRecord 视为第三方),但是我在加载模型时遇到了问题,因此我可以删除 AR 内容...

所以,我一直在做的是:

app/model/city.rb:

class City < ActiveRecord::Base
  # ...
end

spec/model/city_spec.rb:

require 'spec_helper'
describe City do
  # ...
end

默认spec_helper 加载Rails,这是我试图避免的(慢)。我试过这样做:

app/model/city.rb:

require 'active_record'
class City < ActiveRecord::Base
  # ...
end

spec/model/city_spec.rb:

require 'spec_helper_lite'
describe City do
  # ...
end

... 其中spec_helper_lite 中只有require 'pry'(用于调试);它确实加载 Rails。但是,运行具有此更改的规范并检查 City 会给我两个不同的结果。

前者给我:City(id: integer, created_at: datetime, updated_at: datetime, name: string)

后者给我:#&lt;ActiveRecord::Aggregations::ClassMethods:0x3fc61647de40&gt;

当我尝试调用 City.new: ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished 之类的东西时,这会导致问题

我需要做什么才能在不加载 Rails 的情况下加载我的 City 模型,这样我就可以删除 AR 位?

我正在使用ruby 1.9.3rails 3.1.1

【问题讨论】:

标签: ruby-on-rails-3 activerecord rspec


【解决方案1】:

您是否尝试过查看mock_model

这就像一个 ActiveRecord 模型,但不与数据库对话,所以会更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多