【问题标题】:Rspec/Mongoid testing JSON response fails, Expecting field names, but getting fiel Alias insteadRspec/Mongoid 测试 JSON 响应失败,期望字段名称,但获取字段别名
【发布时间】:2013-08-23 09:26:09
【问题描述】:

我正在尝试测试我的控制器的 JSON 响应,

这是我的模型:

class SalesRep < Person
 include Mongoid::Document
end


#Here is Class Person which SalesRep Inherits from:

class Person
include Mongoid::Document

field :nf,  as: :first_name,    type: String
field :nl,  as: :last_name,     type: String
field :ttl, as: :title,         type: String
field :ph,  as: :phone_num,     type: String
field :em,  as: :email,         type: String


attr_accessible :first_name,
                :last_name,
                :title,
                :phone_num ,
                :email

end

这是我的控制器#index:

def index
@sales_reps = SalesRep.all

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @sales_reps, root: false }
end
end

这是我的 rspec 测试,我正在尝试使用以下方法测试 JSON 响应:

  require 'spec_helper'
  describe SalesRepsController do
  let(:valid_attributes) { { first_name: "Seth", last_name: "McFee" } }
  describe "GET index" do
    let!(:sales_rep1){ SalesRep.create! valid_attributes}
    it "return JSON-formated content" do
      get :index, format: :json
      expect(response.body).to have_content sales_rep1.to_json
    end
  end
  end

而且,这里是序列化器:

class SalesRepSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name
end

这是测试输出: 1) SalesRepsController GET 索引返回 JSON 格式的内容

Failure/Error: expect(response.body).to have_content sales_rep1.to_json
expected to find text "{\"_id\":\"52171a4fd7037ee84e000001\",\"em\":null,\"meeting_ids\":[],\"nf\":\"Seth\",\"nl\":\"McFee\",\"ph\":null,\"sex\":1,\"ttl\":null}" in "[{\"id\":\"521718ced7037e15c2000001\",\"first_name\":\"Mark\",\"last_name\":\"Doe\"},{\"id\":\"52171a4fd7037ee84e000001\",\"first_name\":\"Seth\",\"last_name\":\"McFee\"}]"

如您所见,测试期望找到 nf 和 nl ,但它接收字段别名(分别为 first_name 和 last_name ), 我看到了问题,但我不知道如何解决它!

搜索时使用的任何帮助/建议/提示/关键字。非常感谢。

PS,部分数据已被弃用,以使帖子更具可读性,

PPS,对不起我的英语不好。

【问题讨论】:

    标签: ruby-on-rails json testing rspec mongoid


    【解决方案1】:

    现在,在所有 mongoid 版本上,这就是行为。 JSON 序列化不使用编码上的别名字段。有一个 PR 可以修复这个 https://github.com/mongoid/mongoid/pull/2849,它仍在辩论中。如果你想要这个功能,你可以将 PR 合并到你自己的 fork 中。您也可以对票进行投票,以便尽快合并。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2011-10-23
      • 1970-01-01
      相关资源
      最近更新 更多