开发者

Using curl to test Rails routes

开发者 https://www.devze.com 2023-03-11 06:56 出处:网络
I have a model called users that I want to update using an API. The way I thought to do this is by creating an update route and plugging in code that does the updating. I created a test using RSpec an

I have a model called users that I want to update using an API. The way I thought to do this is by creating an update route and plugging in code that does the updating. I created a test using RSpec and it seemed to work, however, I want to actually see the changed data in my database so I was trying to use curl to update my development database.

I tried the command

curl -X PUT -d "attribute1 = value1, attribute2 = value2" http://localhost:3000/users/1

but I got an error

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
&开发者_运维百科lt;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>
.
.
.

Heres's the relevant line in the routes.rb

resources :users, :only => [:create, :update, :destroy]

Here's the relevant code in the 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

And finally here's the spec code that passed

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

I tried to find a good curl tutorial to check my syntax but i could only find examples, so I'm not too sure if the syntax is right.


your PUT data should look like this:

user[attribute1]=value1&user[attribute2]=value2

Similar to the way you'd construct parameters on the query string of a URL.


When calling curl, you would have to send your attributes like this: user[name]=John&... Did you do that?

0

精彩评论

暂无评论...
验证码 换一张
取 消