【发布时间】:2014-01-25 00:35:08
【问题描述】:
我不是在测试 Rails 应用程序。只是把它排除在外。
我正在测试一个连接到相对活跃的服务器的库,通过时间戳限制记录。这些返回的记录随着时间的推移而变化,使测试其他限制变得更加复杂。我需要删除 ActiveRecord::where 方法以返回我自己与我创建的对象的自定义关系以满足我需要的标准。
类似
relation = double(ActiveRecord::Relation)
relation.stub(:[]).and_return( [MyClass.new(...), MyClass.new(...), ...] )
MyClass.stub(:where).and_return( relation )
是我想要的,但这不起作用。我需要它是ActiveRecord::Relation,因为我需要能够在代码中的对象上调用ActiveRecord::where 和ActiveRecord::select。
编辑 2014-01-28
在 lib/call.rb 中
class Call < ActiveRecord::Base
class << self
def sales start_time, end_time
restricted_records = records(start_time, end_time, :agent_id)
#other code
end
#other methods
private
def records start_time, end_time, *select
# I'm leaving in commented code so you can see why I want the ActiveRecord::Relation object, not an Array
calls = Call.where("ts BETWEEN '#{start_time}' AND '#{end_time}'") #.select(select)
raise calls.inspect
#.to_a.map(&:serializable_hash).map {|record| symbolize(record)}
end
end
end
在 spec/call_spec.rb 中
require 'spec_helper'
require 'call.rb'
describe Call do
let(:period_start) { Time.now - 60 }
let(:period_end) { Time.now }
describe "::sales" do
before do
relation = Call.all
relation.stub(:[]).and_return( [Call.new(queue: "12345")] )
Call.stub(:where).and_return( relation )
end
subject { Call.sales(period_start, period_end) }
it "restricts results to my custom object" do
subject
end
end
end
测试输出:
RuntimeError:
#<ActiveRecord::Relation [ #an array containing all the actual Call records, not my object ]>
【问题讨论】:
标签: ruby activerecord rspec mocking relation