2011-12-14 45 views
1

我有一個Rails RESTful Web服務應用程序,它接受來自客戶端的值以遞增數據庫中的值。數據庫值是一個整數,但是當使用rspec來測試代碼時,傳入的值被解釋爲一個字符串。未正確傳遞Rails 3.1 Web服務的數據類型

我使用Rails 3.1和Ruby 1.9.2。

這裏的RSpec的片段:

... 
it "should find Points and return object" do 
    put :update, :username => "tester", :newpoints => [10, 15, 0], :format => :xml 
end 
... 

這裏的控制器代碼:

... 
respond_to do |format| 
    if points.update_attributes([xp + :newpoints[0]][sp + :newpoints[1]][cash +  :newpoints[2]]) 
    format.json { head :ok } 
    format.xml { head :ok } 
... 

XP,SP和現金是從數據庫中值,並已確認爲Fixnum對象數據類型。我得到的錯誤是:

TypeError: String can't be coerced into Fixnum 

如何編寫我的測試,以確保傳遞的參數作爲正確的數據類型傳遞?

如果需要,我可以包含更多的代碼。提前致謝!

回答

0

這讓我有點頭撞,但我發現我錯過了一切。我提出的解決方案絕對不是最好的解決方案,可能會重新編寫,但它的工作,現在,這就足夠了。

換到rspec的片段是建立由符號表示哈希:newpoints

it "should find Points and return object" do 
    put :update, :username => "tester", :newpoints => {"experience_points" => 10, "shame_points" => 15, "gold" => 0}, :format => :xml 
end 

中需要一些調整控制該請求的處理,但這裏的相關部分:

class PointsController < ApplicationController 
    #before_filter :authenticate, :only => :update 
    before_filter :must_specify_user 
    before_filter :fix_params 
    before_filter :clean_up 
    respond_to :html, :xml, :json 

    def fix_params 
    if params[:points] 
     params[:points][:user_id] = @user.id if @user 
    end 
    end 

def clean_up 
    @newpoints = params[:newpoints] 
    @experience = @newpoints["experience_points"] 
    @shame = @newpoints["shame_points"] 
    @gold = @newpoints["gold"] 
    @xp = @experience.to_i 
    @sp = @shame.to_i 
    @cash = @gold.to_i 
end 

def update 
    points = Points.find_by_user_id(@user.id, params[:id]) 
    xp = points.experience_points 
    sp = points.shame_points 
    cash = points.gold 
    final_experience = xp += @xp 
    final_shame = sp += @sp 
    final_gold = cash += @cash 
    final_points = {:experience_points => final_experience, :shame_points => final_shame, :gold => final_gold} 
    if_found points do 
    respond_to do |format| 
     if points.update_attributes!(params[final_points]) 
     format.json { head :ok } 
     format.xml { head :ok } 
     else 
     format.json { render :nothing => true, :status => "401 Not Authorized"} 
     format.xml { render :nothing => true, :status => "401 Not Authorized"} 
     end 
    end 
    end 
end 
end 

很明顯,可以做很多事情來使這個後續DRY和什麼不是,所以任何建議仍然歡迎。提前致謝!