尝试了解围绕 Tire gem 进行测试的语法。
此 Controller 规范(默认来自脚手架模板)失败
describe "GET index" do
it "assigns all reports as @reports" do
report = Report.create! valid_attributes
get :index, {}, valid_session
assigns(:reports).should eq([report])
end
end
因为
Failure/Error: assigns(:reports).should eq([report])
TypeError:
can't convert Tire::Results::Collection to Array (Tire::Results::Collection#to_ary gives Tire::Results::Collection)
如何编写规范,使其需要 Tire 结果 集合而不是事件记录对象数组?或者,有更好的方法来解决这个问题吗?
FWIW-
class ReportsController < ApplicationController
def index
@reports = Report.search(params)
end
...
和型号:
class Report < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
...
def self.search(params)
tire.search(load: true) do
query { string params[:query] } if params[:query].present?
end
end
...
最佳答案
我意识到这是一个非常迟到的答案,但是嘿,开始了。
Rspec 正在进行直接比较。它有一个集合,并尝试将其与数组进行比较。然而,Tire 定义了对数组的强制转换,实际上并不返回数组(为什么,我不确定,这对我来说听起来很烦人!)
鉴于您不打算比较数组,那么我快速浏览了 Collection 的源代码:https://github.com/karmi/tire/blob/master/lib/tire/results/collection.rb
好吧,我们没有一个有用的 to_ary...但是我们确实有一个each,并且包含了Enumerable。这意味着我们基本上拥有数组可用的所有内容。
那么,鉴于此,我们实际上想在这里做什么?我们想要检查 @report 在 @reports 中是否可用。好吧,我们有可枚举的,并且快速检查期望源( https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/include.rb#L38 )说 include 将映射到 include?在数组对象上。
所以,简而言之,尝试将您的测试更改为:
describe "GET index" do
it "assigns all reports as @reports" do
report = Report.create! valid_attributes
get :index, {}, valid_session
assigns(:reports).should include(report)
end
end
关于ruby-on-rails - RSpec & Tire gem:测试 Tire::Results::Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12377569/