2017-04-01 26 views
0

開始,在我的要求規範sites.spec.rb我有這樣的測試:Rails的API後要經過PARAMS但漸漸空虛

describe "POST /v1/sites" do 

    let(:valid_attributes) { { url: "www.example.com", site_code: "123456" } } 

    context 'when the request is valid' do 
     before { post v1_sites_path, params: valid_attributes } 

     it 'creates a site' do 
     expect(json['url']).to eq("www.example.com") 
     expect(json['site_code']).to eq("123456") 
     end 

     it 'returns status code 201' do 
     expect(response).to have_http_status(201) 
     end 
    end 

然後我得到「創建網站」一個失敗的測試...

1) Sites POST /v1/sites when the request is valid creates a site 
    Failure/Error: expect(json['url']).to eq("www.example.com") 

     expected: "www.example.com" 
      got: ["can't be blank"] 

     (compared using ==) 
    # ./spec/requests/sites_spec.rb:61:in `block (4 levels) in <top (required)>' 
    # ./spec/rails_helper.rb:84:in `block (3 levels) in <top (required)>' 
    # ./spec/rails_helper.rb:83:in `block (2 levels) in <top (required)>' 

現在這在技術上是有道理的,因爲我的網站模型已驗證:url,:site_code,presence:true。所以測試失敗,因爲該帖子沒有正確傳遞參數。

最後,這裏是控制器:

module Api::V1 
    class SitesController < BaseApiController 
    before_action :set_site, only: [:show, :update, :destroy] 

    # GET /sites 
    def index 
     @sites = Site.all 

     render json: @sites 
    end 

    # GET /sites/1 
    def show 
     render json: @site 
    end 

    # POST /sites 
    def create 
     @site = Site.new(site_params) 

     if @site.save 
     render json: @site, status: :created, location: @site 
     else 
     render json: @site.errors, status: :unprocessable_entity 
     end 
    end 

    # PATCH/PUT /sites/1 
    def update 
     if @site.update(site_params) 
     render json: @site 
     else 
     render json: @site.errors, status: :unprocessable_entity 
     end 
    end 

    # DELETE /sites/1 
    def destroy 
     @site.destroy 
    end 

    private 
     # Use callbacks to share common setup or constraints between actions. 
     def set_site 
     @site = Site.find(params[:id]) 
     end 

     # Only allow a trusted parameter "white list" through. 
     def site_params 
     # params.require(:data).require(:attributes).permit(:url, :side_code, :user_id) 
     # params.require(:site).permit(:url, :side_code, :user_id) 
     params.fetch(:site, {}).permit(:url, :side_code) 
     end 
    end 
end 

我猜測,我傳遞的參數後爲Rails API的方式也許是未格式化或正確或別的東西完全。我在測試塊中玩params嘗試數據:{attributes:valid_attributes}沒有運氣。

任何想法或建議,非常感謝!

回答

0

此問題確實是由於我在測試塊中傳遞給POST請求的參數的格式所致。我通過命令行測試了POST,並觀察了Rails服務器以查看參數是如何通過的。他們是這樣的:

Parameters: {"site_code"=>"123456", "url"=>"www.updated.com", "subdomain"=>"api", "id"=>"2", "site"=>{"site_code"=>"123456", "url"=>"www.updated.com"}} 

然後在我的sites_spec.rb,我複製這種格式的POST請求的有效PARAMS:

let(:valid_attributes) { { "site"=>{"url"=>"www.example.com", "user_id"=>user_id, "site_code"=>"123456"} } } 

這工作。參數的JSON格式需要在測試塊中進行格式化,就像它們是真實的JSON請求一樣。