Rails Api Rspec测试在路线上采用参数

时间:2014-09-24 07:14:05

标签: ruby-on-rails ruby ruby-on-rails-4 rspec rspec-rails

的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

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

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

我有很多学生的名字。据我所知,这两个应该是获取路由/获取请求。我两个都得到同样的错误: -

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)>'

它们应该是POST路由。我错过了什么。我做错了吗?请有人帮我解决这个问题。

2 个答案:

答案 0 :(得分:3)

我认为这是路由匹配错误。此调用中缺少参数字母。

替换

get :name_starts_with

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

我认为这会解决您的错误。

答案 1 :(得分:0)

我知道这听起来很愚蠢,但是你的StudentsController继承自ApplicationController吗? (ApplicationController继承自ActionController :: Base

...如果您已在控制器中声明了render:json,我不确定您是否需要@ students.to_json。只需把渲染json:@students