【发布时间】:2015-07-17 01:43:40
【问题描述】:
尝试让我的投票方法通过时,我在 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"}
现在我可以在服务器上投赞成票和反对票,这只是我的测试不起作用。
这是我的代码:
votes_controller_spec.rb
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
votes_controller.rb
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
routes.rb
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
相关的 Rake 路由
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 生成错误吗?
【问题讨论】:
-
看起来路径应该是
/posts/:id/up-vote。rake routes返回什么,与您传递给测试的路径相同吗? -
我在上面添加了相关的 rake 路由。老实说,我不知道如何通过有关这些路线的嵌套路径...
标签: ruby-on-rails ruby rspec