2013-07-11 133 views
1

我在測試控制器的更新方法時遇到了一些問題,但我在測試中遇到了無路徑匹配問題。儘管如此,通過瀏覽器提交表單仍然有效。測試導軌4控制器

我的routes文件:

namespace :merchant do 
    resources :users 
    get '/signup', to: "users#new" 
end 

我的控制器:

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

我的測試:

test "should update user" do 
    user = users(:jon) 
    user.first_name="Jonas" 
    put :update, :merchant_user =>user.attributes 
    assert_response :success 

結果:

1) Error: 
Merchant::UsersControllerTest#test_should_update_user: 
ActionController::UrlGenerationError: No route matches {:merchant_user=> {"id"=>"846114006", "email"=>"[email protected]", "first_name"=>"Jonas", "last_name"=>"Sims", "password_digest"=>"$2a$10$LVbV7pkd7li8sobYEauoS.4JVA2ZHzAXgPFbyiojYqgcDBHUE9bXW", "type"=>"Merchant::User", "created_at"=>"2013-07-11 22:59:41 UTC", "updated_at"=>"2013-07-11 22:59:41 UTC"}, :controller=>"merchant/users", :action=>"update"} 
test/controllers/merchant/users_controller_test.rb:45:in `block in <class:UsersControllerTest>' 

任何提示?

回答

2

從您的路線看起來,它似乎期待id參數。

如果您在命令行做rake routes它可能會顯示,看起來像

/merchant/users/:id/update

如果您在id這樣put :update, id: user.id, merchant_user: user.attributes通過它應該工作的路線。

+0

稍後會進行測試,但看起來這可能是新手在Rails上再次拾起的問題:)。 –

+0

就是這樣。感謝Mohamad和Leo Correa。雖然都幫助了我,但我會接受Leo的回答。 –

3

您需要傳遞用戶的id才能正常運行測試。

試試這個:

put :update, id: user.id, merchant_user: {} 

因爲路由器預計resource/:id你看到這個錯誤,但你不能傳遞ID。

Users#update是一個成員動作,它需要一個id。路由器期望用戶ID參數:/users/:id/update。如果沒有該方法,則該方法無法找到想要更新的用戶。