简体   繁体   English

Rails Api Rspec测试在路线上进行参数

[英]Rails Api Rspec Test that takes params on route

routes.rb routes.rb

get 'students/name_starts_with/:letter', to: 'students#name_starts_with'
get 'students/with_last_name/:last', to: 'students#with_last_name'

students_controller.rb students_controller.rb

def name_starts_with
  @students = Student.all.select{|s| s.first_name.start_with?(params[:letter]}
  render json: @students.to_json
end

def with_last_name
  @students = Student.all.select{|s| s.last_name == params[:last]}
  render json: @students.to_json
end

students_controller_spec.rb students_controller_spec.rb

context '#name_starts_with' do
  let!(:first_student){Student.create(first_name: 'John', last_name: 'Doe'}
  it "starts with #{first_student.first_name.split('').first}" do
    get :name_starts_with
    expect(response.status).to eq(200)
    expect(first_student.first_name.split('').first).to be('J')
  end
end

context '#with_last_name' do
  let!(:first_student){Student.create(first_name: 'John', last_name: 'Doe'}
  it "has last name #{first_student.last_name}" do
    get :with_last_name
    expect(response.status).to eq(200)
    expect(first_student.last_name).to be('Doe')
  end
end

I have seeded bunch of student names. 我播下了一堆学生名字。 As far as I know both of these should be get routes/get requests. 据我所知,这两个都应该是获取路由/获取请求。 I am getting same error for both:- 我两个都遇到相同的错误:

Failure/Error: get :name_starts_with
     ActionController::UrlGenerationError:
       No route matches {:action=>"name_starts_with", :controller=>"students"}
     # ./spec/controllers/students_controller_spec.rb:45:in `block (3 levels) in <top (required)>'

Should they be POST routes instead. 它们应该是POST路由。 Am I missing something. 我错过了什么吗? Am I doing whole thing wrong. 我做错了什么吗? Can somebody please help me solve this issue please. 有人可以帮我解决这个问题吗?

I think this is route matching error. 我认为这是路线匹配错误。 parameter letter is missing in this call. 此调用中缺少参数字母。

Replace 更换

get :name_starts_with

with

get :name_starts_with, letter: first_student.first_name.split('').first

I think this will fix your error. 我认为这可以解决您的错误。

I know this sounds stupid, but is your StudentsController inheriting from ApplicationController? 我知道这听起来很愚蠢,但是您的StudentsController是从ApplicationController继承的吗? (ApplicationController inherits from ActionController::Base (ApplicationController继承自ActionController :: Base

...and I'm not sure if you need the @students.to_json if you already declared render :json in your controller. ...并且如果您已经在控制器中声明render:json,我不确定是否需要@ students.to_json。 just put render json: @students 只需将渲染json:@students

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

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