我正在尝试为我的应用测试create方法,但出现以下错误:
1) RanksController POST #create when user is sign in creates rank
Failure/Error: post :create, params: { user: user, movie: movie }
ActionController::UrlGenerationError:
No route matches {:action=>"create", :controller=>"ranks", :movie=>#<Movie
id: 1, title: "excepturi", description: "Vilicus crur volutabrum balbus cum
vulgaris statua...", released_at: "1998-03-22 00:00:00", avatar: nil,
genre_id: 1, created_at: "2019-01-15 14:45:10", updated_at: "2019-01-15
14:45:10">, :user=>#<User id: 1, email: "deja@ruel.co", created_at: "2019-
01-15 14:45:10", updated_at: "2019-01-15 14:45:10", phone_number: name: "">}
我发现了很多潜在的解决方案,但它们对我没有用。
ranks_controller_spec
RSpec.describe RanksController, type: :controller do
let(:user) { FactoryBot.create(:user) }
let(:movie) { FactoryBot.create(:movie) }
describe "POST #create" do
context "when user is sign in" do
before { sign_in(user) }
it "creates rank" do
expect do
post :create, params: { user: user, movie: movie }
end.to change(Rank, :count).by(1)
expect(response).to have_http_status(:redirect)
end
end
end
ranks_controller
class RanksController < ApplicationController
before_action :set_movie, only: %i[create destroy]
def create
Rank.create!(user: current_user, movie: @movie)
redirect_to @movie
end
def destroy
rank = @movie.ranks.find(params[:id])
rank.destroy!
redirect_to @movie
end
private
def set_movie
@movie = Movie.find(params[:movie_id])
end
end
show.html.haml
- if @rank
= link_to 'Vote', movie_rank_path(@movie, @rank), method: :delete
- else
= link_to 'Vote', movie_ranks_path(@movie), method: :post
在movies_controller.rb中显示动作:
def show
@movie = Movie.find(params[:id])
@like = @movie.likes.find_by(user: current_user)
end
routes.rb
resources :movies, only: [:index, :show] do
resources :ranks, only: %i[create destroy]
member do
get :send_info
end
collection do
get :export
end
end
在网络版本中,所有功能均按预期运行
答案 0 :(得分:1)
尝试传递id而不是像下面这样的对象
post :create, params: { user_id: user.id, movie_id: movie.id }
我认为您根本不需要传递user
或user_id
,因为您没有在create action上使用它。 current_user
的创建操作应返回您在before
块上登录的用户。