2011-06-06 43 views
1

我有一個叫做用戶的模型,我想用API來更新。我認爲這樣做的方式是創建一個更新路由並插入執行更新的代碼。我創建了一個使用RSpec的測試,它似乎工作,但是,我想實際上看到我的數據庫中更改的數據,所以我試圖使用curl來更新我的開發數據庫。使用curl來測試Rails路線

我試着命令

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] 

下面是相關的代碼在控制器

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 

我試圖找到一個很好的捲曲教程來檢查我的語法,但我只能找到的例子,所以我也不太清楚,如果語法是正確的。

回答

1

PUT數據應該是這樣的:

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

類似你構建一個URL的查詢字符串參數的方式。

+0

謝謝,剛剛嘗試過,我得到相同的錯誤 – ageorgie 2011-06-06 19:21:32

+0

對不起 - 我只是看看你的控制器代碼。既然你有'params [:user] [:attribute1]''等你的屬性實際上需要封裝在用戶[...]。請看我最新的回覆。 – 2011-06-06 19:27:26

1

調用curl時,您將不得不發送如下屬性:user [name] = John & ... 您是否這樣做?

+0

不,我沒有 - 這擺脫了錯誤消息,但用戶信息沒有得到更新。 – ageorgie 2011-06-06 19:26:05

+0

此外,你必須設置沒有用戶命名空間的id,所以id = 15&user [name] = john&...此外,可能的是,rails沒有正確接收http動詞,嘗試使用額外的post請求參數_method = put – moritz 2011-06-06 19:28:59

+0

所以我試着 'curl -X POST -d「_method = PUT&id = 1&user [attr1] = val1&user [attr2] = val2」http:// localhost:3000/users/1' 但它仍然沒有不會更新。我也試過 'curl H「X-HTTP-Method-Overrride:PUT」-X POST -d「id = 1&user [attr1] = val1&user [attr2] = val2」http:// localhost:3000/users/1' ,並給了我一個錯誤,說沒有路由/用戶/ 1 – ageorgie 2011-06-06 19:48:47