2013-08-23 40 views
2

我想測試我的JSON響應控制器,Rspec的/ Mongoid測試JSON響應失敗時,期待的字段名,但得到FIEL別名來代替

這裏是我的模型:

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 

這裏是我的控制器#指數:

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 

,這裏是測試outpout: 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,對不起我的英語不好。

回答

0

現在,在所有的mongoid版本上,這就是行爲。 JSON序列化不使用編碼上的別名字段。有一個PR正在解決這個仍在辯論中的https://github.com/mongoid/mongoid/pull/2849。如果你想要這個功能,你可以將PR合併到你自己的分支中。您也可以在票上進行投票,以便儘早合併。