【发布时间】:2015-11-24 10:03:24
【问题描述】:
我有一个奇怪的情况。 我的 routes.rb 中有这样的代码:
concern :votable do
post :vote_up, on: :member, controller: :votes
post :vote_down, on: :member, controller: :votes
end
resources :questions, concerns: [:commentable, :votable], shallow: true do
resources :answers, concerns: [:commentable, :votable]
end
所以,它通过“帖子”为我提供了帮助 vote_up_question 和 vote_up_answer:
vote_up_answer POST /answers/:id/vote_up(.:format) votes#vote_up
vote_down_answer POST /answers/:id/vote_down(.:format) votes#vote_down
vote_up_question POST /questions/:id/vote_up(.:format) votes#vote_up
vote_down_question POST /questions/:id/vote_down(.:format) votes#vote_down
我的投票控制器:
before_action :load_parent
def vote_up
current_user.vote_for(@parent)
redirect_to :back, notice: "Voted up"
end
private
def load_parent
resource, id = request.path.split("/")[1, 2]
@parent = resource.singularize.classify.constantize.find(id)
end
一切都很完美,但是!
我想用 RSpec 测试 load_parent 方法:
RSpec.describe VotesController, type: :controller do
let(:question) {create(:question)}
let(:answer) {create(:answer, user_id: user, question_id: question)}
let(:user) {create(:user)}
before(:each) do |example|
sign_in user if example.metadata[:sign_in]
request.env["HTTP_REFERER"] = question_path(question) if example.metadata[:redirect_back]
end
describe 'POST #vote_up', sign_in: true, redirect_back: true do
it 'should assign question to @parent' do
post vote_up_question_path(question)
expect(assigns(:parent)).to eq 'question'
end
end
end
这里有个问题:
ActionController::UrlGenerationError:
No route matches {:action=>"/questions/1/vote_up", :controller=>"votes"}
怎么了?我也尝试了不同的方法来明确路线,比如post :vote_up, question_id: question,但它不起作用
【问题讨论】:
-
你能显示
rake routes的输出吗? -
将部分内容添加到问题中。
-
你试过
post :vote_up, id: question.id吗? -
是的,结果很奇怪——
ActiveRecord::RecordNotFound: Couldn't find Answer with 'id'=1 -
我可以测试答案案例,但不能测试问题案例 - 所以它不是正确的解决方案。而且,我仍然无法理解为什么会发生这种情况
标签: ruby-on-rails rspec