使用curl测试Rails路由
我有一个名为用户的模型,我想使用API进行更新。 我认为这样做的方法是创建更新路由并插入执行更新的代码。 我使用RSpec创建了一个测试,它似乎工作,但是,我想实际看到我的数据库中更改的数据,所以我试图使用curl来更新我的开发数据库。
我试过这个命令
curl -X PUT -d "attribute1 = value1, attribute2 = value2" http://localhost:3000/users/1
但是我收到了一个错误
Action Controller: Exception caught . . .NoMethodError in UsersController#update
You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]. . .
Heres是routes.rb中的相关行
resources :users, :only => [:create, :update, :destroy]
这是控制器中的相关代码
def update @user = User.find(params[:id]) if params[:user][:attribute1] == ("x" || "y" || "z") params[:user][:attribute3] = Time.now end @user.update_attributes(:user) render :nothing => true end
最后这里是通过的规范代码
describe "PUT 'update'" do before(:each) do @user = Factory(:user) end describe "success" do it "should be successful" do put :update, :id => @user, :user => { :attribute1 => "x", :attribute2 => "xyz"} response.should be_success end it "should update attribute" do old_attribute = @user.attribute3 put :update, :id => @user, :user => { :attribute1 => "x", :attribute2 => "xyz"} @user.attribute3 != old_attribute end end end
我试图找到一个好的curl教程来检查我的语法,但我只能找到例子,所以我不太确定语法是否正确。
您的
PUT
数据应如下所示:
user[attribute1]=value1&user[attribute2]=value2
与您在URL的查询字符串上构造参数的方式类似。
调用curl时,你必须发送你的属性:user [name] = John&…你做到了吗?