2013-07-11 80 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。如果没有该方法,则该方法无法找到想要更新的用户。