我试图让我的upvote方法通过时,我的RSpec中一直收到以下错误:
Failures:
1) VotesController#up_vote adds an up-vote to the post
Failure/Error: post( :up_vote, post_id: @post.id )
ActionController::UrlGenerationError:
No route matches {:action=>"up_vote", :controller=>"votes", :post_id=>"1"}
现在,当我在服务器上时,我可以进行upvote和downvote,这只是我的测试不起作用。
这是我的代码:
require 'rails_helper'
describe VotesController do
include TestFactories
include Devise::TestHelpers
describe '#up_vote' do
it "adds an up-vote to the post" do
request.env["HTTP_REFERER"] = '/'
@user = authenticated_user
@post = associated_post
sign_in @user
expect {
post(:up_vote, post_id: @post.id)
}.to change { @post.up_votes }.by 1
end
end
end
class VotesController < ApplicationController
before_action :load_post_and_vote
def up_vote
update_vote!(1)
redirect_to :back
end
def down_vote
update_vote!(-1)
redirect_to :back
end
def update_vote!(new_value)
if @vote
authorize @vote, :update?
@vote.update_attribute(:value, new_value)
else
@vote = current_user.votes.build(value: new_value, post: @post)
authorize @vote, :create?
@vote.save
end
end
private
def load_post_and_vote
@post = Post.find(params[:post_id])
@vote = @post.votes.where(user_id: current_user.id).first
end
end
Rails.application.routes.draw do
devise_for :users
resources :users, only: [:update]
resources :questions
resources :advertisements
resources :topics do
resources :posts, except: [:index] do
resources :summaries, only: [:create, :new, :show]
resources :comments, only: [:create, :destroy]
post '/up-vote', to: 'votes#up_vote', as: :up_vote
post '/down-vote', to: 'votes#down_vote', as: :down_vote
end
end
get 'about' => 'welcome#about'
get 'contact' => 'welcome#contact'
root to: 'welcome#index'
end
module TestFactories
def associated_post(options={})
post_options = {
title: 'Post title',
body: 'Post bodies must be pretty long.',
topic: Topic.create(name: 'Topic name'),
user: authenticated_user
}.merge(options)
Post.create(post_options)
end
def authenticated_user(options={})
user_options = {email: "email#{rand}@fake.com", password: 'password'}.merge(options)
user = User.new(user_options)
user.skip_confirmation!
user.save
user
end
end
topic_post_up_vote POST /topics/:topic_id/posts/:post_id/up-vote(.:format) votes#up_vote
topic_post_down_vote POST /topics/:topic_id/posts/:post_id/down-vote(.:format) votes#down_vote
为什么我收到此URL生成错误的任何想法?
答案 0 :(得分:2)
我认为您只需要将topic_id
传递给post方法,如下所示:post( :up_vote, post_id: @post.id, topic_id: @post.topic.id )
答案 1 :(得分:0)
我最终将routes.rb文件切换到下面,并使上面的vote_controller_spec.rb工作。
myobject.myset = myobject.myset.union(yourset)