ruby-on-rails - 使用 curl 测试 Rails 路由

标签 ruby-on-rails ruby-on-rails-3 api curl routes

我有一个名为 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/

相关文章:

ruby-on-rails - 如何以正确的方式在 Rails 中执行 history.js?

ruby-on-rails - RSpec:避免使用允许接收的任何实例

javascript - 如何在 Rails 3.1 Assets 管道中获取 EXTJS 4?

ruby-on-rails-3 - 如何从 nginx 而不是 unicorn 提供缓存的 ruby​​ 应用程序?

Scala Future 错误处理与任一

ruby-on-rails - 有条件的 rails 字段

html - 如何在 ruby​​ on rails 3.2 中使用 id 显示字段名称

ruby-on-rails - 如何为邮件拦截器编写 RSpec?

c# - dotnet core api 文件夹结构

python - 将 API 转换为 Pandas DataFrame