Rails:路由错误测试控制器的更新方法

时间:2014-10-24 01:55:58

标签: ruby-on-rails rspec

我正在研究学习TDD,并且在我的控制器规范中遇到了一个我似乎无法解决的更新方法的路由错误:

PeopleController#update when a person is valid redirects to person
 Failure/Error: put :update, person: { first_name: "Joe" }
 ActionController::UrlGenerationError:
   No route matches {:action=>"update", :controller=>"people", :person=>{:first_name=>"Joe"}}

people_controller.rb

def edit
end

def update
  if @person.update(person_attributes)
    redirect_to @person, notice: 'Person was successfully updated.'
  else
    render :edit
  end
end

people_controller_spec.rb

describe "#update" do
  context "when a person is valid" do
    it "redirects to person" do
      person = Person.create(first_name: "Bob")
      allow(person).to receive(:update).and_return(true)
      allow(Person).to receive(:update).
        with(first_name: "Joe").
        and_return(person)

      put :update, person: { first_name: "Joe" } 
      expect(response).to redirect_to(person_path(person))
    end
  end
end

的routes.rb

Rails.application.routes.draw do
  resources :people, only: [:new, :create, :show, :edit, :update]
end

您如何建议测试此控制器操作?

感谢。

1 个答案:

答案 0 :(得分:1)

在people_controller_spec.rb上使用put :update, person: { first_name: "Joe" }

更改put :update, id: person.id, person: { first_name: "Joe" }

这必须做到这一点。