简体   繁体   English

Rspec控制器测试中未定义的方法route_name

[英]Undefined method route_name in Rspec controller test

When running my controller test, I get this error: 运行控制器测试时,出现以下错误:

NoMethodError:
   undefined method `api_challenge_url' for #<Api::V1::ChallengesController:0x007f829b233460>

Which, is in fact, not a route that exists. 实际上,这不是一条存在的路线。 My routes file looks like this: 我的路线文件如下所示:

namespace :api, { format: :json, constraints: { subdomain: 'api' }, path: '/'}  do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
  resources :users, only: [:show, :create, :update, :destroy] do
    resources :challenges, only: [:create, :show]
  end
 end
end

And my controller test looks like this: 我的控制器测试如下所示:

RSpec.describe Api::V1::ChallengesController, type: :controller do

describe "POST #create" do
 context "when successfully created" do

  before(:each) do
    @user = FactoryGirl.create(:user)
    @challenge_attributes = FactoryGirl.attributes_for(:challenge)
    post :create, user_id: @user.id, challenge: @challenge_attributes, format: :json
  end

  it "should render the JSON for the created challenge" do
    challenge_response = JSON.parse(response.body, symbolize_names: true)
    expect challenge_response[:description].to eql @challenge_attributes["description"]
    expect challenge_response[:title].to eql @challenge_attributes["title"]
  end
 end
end

end

But for the life of me, I can't why it's calling the wrong route name. 但是对于我的一生,我无法理解为什么它使用了错误的路线名称。 The output of the relevant part of the rake routes looks like this: rake routes相关部分的输出如下所示:

api_user_challenges POST   /users/:user_id/challenges(.:format)     api/v1/challenges#create {:subdomain=>"api"}

I've tried a few different formats in the post method, is there some idiomatic way of doing this that I'm missing? 我在post方法中尝试了几种不同的格式,是否缺少一些惯用的方法来做到这一点?

Try adding some configuration to include url helpers into your test suite: 尝试添加一些配置,以将url帮助器包括到您的测试套件中:

RSpec.configure do |c|
  c.include Rails.application.routes.url_helpers
  # Other configurations ...
end

And if you prefer using xxx_url over xxx_path , remember to config action_controller.default_url_options in your config/environments/test.rb , for example: 而且,如果您更喜欢使用xxx_url不是xxx_path ,请记住在config/environments/test.rb配置action_controller.default_url_options ,例如:

config.action_controller.default_url_options = {
  host: 'www.mysite.org',
  protocol: 'https'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM