我有一个Rails RESTful Web服务应用程序,它接受来自客户端的值以增加数据库中的值。数据库值是一个整数,但是当使用rspec测试代码时,传入的值被解释为字符串。
我正在使用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和cash是数据库中的值,并且已经过验证为Fixnum数据类型。我得到的错误是:
TypeError: String can't be coerced into Fixnum
如何编写测试以确保传递的参数作为正确的数据类型传递?
如果需要,我可以包含更多代码。提前谢谢!
答案 0 :(得分:0)
它让我有点头撞,但我发现我错过了一切。我提出的解决方案绝对不是最好的解决方案,可能会被重写,但它现在有效,而且现在已经足够了。
对rspec片段的更改是创建由symbol: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
显然,要做到这一点可以做很多事情,以便干预和不做什么,所以任何建议仍然是受欢迎的。提前谢谢!