我有一个名为 users 的模型,我想使用 API 更新它。我想这样做的方法是创建一个更新路由并插入执行更新的代码。我使用 RSpec 创建了一个测试,它似乎可以正常工作,但是,我想在我的数据库中实际看到更改的数据,所以我尝试使用 curl 来更新我的开发数据库。
我试过命令
curl -X PUT -d "attribute1 = value1, attribute2 = value2" http://localhost:3000/users/1
但是我得到了一个错误
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
<style>
.
.
.
</style>
</head>
<body>
<h1>
NoMethodError
in UsersController#update
</h1>
<pre>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.[]</pre>
.
.
.
这是 routes.rb 中的相关行
resources :users, :only => [:create, :update, :destroy]
Controller 中的相关代码如下
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 的查询字符串上构造参数的方式。
关于ruby-on-rails - 使用 curl 测试 Rails 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256830/