Jos*_*rey 3 ruby testing rspec ruby-on-rails
我一直在寻找可以解释我遇到的问题的东西。我可能遗漏了一些简单的东西,所以我希望有人能发现我的错误。
Rails.application.routes.draw do
get 'auth/:provider/callback', to: 'sessions#create', as: 'login'
get 'auth/failure', to: redirect('/')
get 'signout', to: 'sessions#destroy', as: 'signout'
resources :sessions, only: [:create, :destroy]
resources :home, only: [:show]
resources :static_pages, only: [:show]
resources :habits
root to: "home#show"
get '/started' => 'home#started'
end
Run Code Online (Sandbox Code Playgroud)
路线:
habit GET /habits/:id(.:format) habits#show
PATCH /habits/:id(.:format) habits#update
PUT /habits/:id(.:format) habits#update
DELETE /habits/:id(.:format) habits#destroy
Run Code Online (Sandbox Code Playgroud)
习惯控制器:
def update
if params[:name].present? && params[:description].present?
Habit.habit_edit(@current_habit, form_params)
flash[:success] = "Edited habit: " + @current_habit.name + '!'
redirect_to habit_path(:id => session[:user_id])
else
flash[:notice] = "Habit must have a name and a description"
redirect_to edit_habit_path(:id => @current_habit.id)
end
end
Run Code Online (Sandbox Code Playgroud)
HabitsControllerSpec:
describe "#update" do
it "should update the habit name/description" do
form_params = {
params: {
name: "hello",
description: "hello"
}
}
post :create, form_params
@current_habit = Habit.first
form_params = {
params: {
name: "new",
description: "shit"
}
}
**patch "habits/1", form_params**
end
Run Code Online (Sandbox Code Playgroud)
问题:
1) HabitsController#update should update the habit name/description
Failure/Error: patch "habits/1", form_params
ActionController::UrlGenerationError:
No route matches {:action=>"habits/1", :controller=>"habits",
:description=>"shit", :name=>"new"}
# ./spec/controllers/habits_controller_spec.rb:85:in `block (3
levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这不起作用。我尝试了很多不同的方法来发出补丁请求,但似乎无法弄清楚如何让这个测试工作。再说一次,我相信这很简单。如果我遗漏了任何重要信息,请告诉我。谢谢
好吧想通了。首先,我为这个习惯建立了一个工厂,只是为了澄清事情。我一直在搞乱语法并得出了正确的答案。
form_params = {
params: {
name: "new",
description: "shit"
}
}
patch :update,id: 1, form_params
Run Code Online (Sandbox Code Playgroud)
这告诉我错误的参数数量,我最终意识到我需要通过我的 form_params 传递 id。就像我说的,小错误。
正确代码:
form_params = {
id: 1,
name: "new",
description: "shit",
}
patch :update, params: form_params
Run Code Online (Sandbox Code Playgroud)