gpt4 book ai didi

ruby-on-rails - Rspec "no route matches"

转载 作者:行者123 更新时间:2023-12-04 06:24:24 25 4
gpt4 key购买 nike

我有一个奇怪的情况。
我的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

所以,它给了我 helper vote_up_questionvote_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

我的投票 Controller :
  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

一切都很完美,但是!
我想测试一下 load_parent使用 RSpec 的方法:
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 ,但它不起作用

最佳答案

尝试:

 let!(:question) {create(:question)}
let!(:user) {create(:user)}
let!(:answer) {create(:answer, user_id: user, question_id: question)}

let 是惰性求值的,所以如果它没有在这个块中被调用,它可能是未定义的。

然后做:
 describe 'POST #vote_up', sign_in: true, redirect_back: true  do
it 'should assign question to @parent' do
post :vote_up, id: question.id
expect(assigns(:parent)).to eq 'question'
end

结尾

关于ruby-on-rails - Rspec "no route matches",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33890617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com