2014-01-06 25 views
3

我是Rails的新手,已經開始研究一個新項目。但我無法找到我的更新控制器的確切解決方案,這是我的更新控制器。如何爲控制器的更新操作寫一個rspec?

 
def update 
    respond_to do |format| 
     if @wallet.update(wallet_params) 
     format.html { redirect_to @wallet, notice: 'Wallet was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: 'edit' } 
     format.json { render json: @wallet.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

在我的錢包表中我有id,user_id,balance,name。我曾嘗試

 
    describe "PUT #update" do 
    it "should update the wallet" do 
     put :update, id :@wallet.id :wallet{ :name => "xyz", :balance => "20.2"} 
    end 
    end 

甚至嘗試一些東西 RSpec test PUT update actionHow to write an RSpec test for a simple PUT update?,但依然沒能解決問題。

+0

試試這個可能對你有幫助 http://stackoverflow.com/questions/7060521/i-am-having-trouble-testing-my-controllers-update-action-using-rs-what-what- -am -i –

+2

問題是什麼。你有錯誤嗎?你的測試沒有做出斷言?發生了什麼?你期望發生什麼? –

回答

2

如果您使用的是Rails 4,請使用PATCH而不是PUT; PUT仍然有效,但PATCH現在是首選。要測試,請嘗試以下操作:

describe "PATCH #update" do 
    context "with good data" do 
    it "updates the wallet and redirects" do 
     patch :update, id: @wallet.id, wallet: { name: "xyz", balance: "20.2"} 
     expect(response).to be_redirect 
    end 
    end 
    context "with bad data" do 
    it "does not change the wallet, and re-renders the form" do 
     patch :update, id: @wallet.id, wallet: { name: "xyz", balance: "two"} 
     expect(response).not_to be_redirect 
    end 
    end 
end 

您可以使expect子句更具體,但這是一個開始。如果您想測試代碼的json部分,只需將format: 'json'添加到params散列。

相關問題