2

我正在尝试测试我的控制器的 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

这是我的 Controller#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

这是我试图测试 JSON 响应的 rspec 测试:

  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,对不起我的英语不好。

4

1 回答 1

0

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

于 2013-08-25T01:21:21.637 回答