RSpec 路由规范 POST 请求问题

RSpec Routing Spec POST Request Problems

我是 Rails 开发人员的 Ruby,我正在使用 RSpec 测试一个相当简单的 Rails 应用程序。我正在编写一些路由规范,然后我遇到了这个问题:

我的路线是这样的:

Rails.application.routes.draw do
  root 'trip_plans#index'
  resources :trip_plans
end

所以我有一个像 post /trip_plans 这样的路线来创建新计划并触发 trip_plans#create 行动。

我的路由规范文件 spec/routing/trip_plans_spec.rb 如下所示:

require 'rails_helper'

RSpec.describe 'trip_plans routes', type: :routing do
  describe 'creating a new plan' do
    it 'creates a new plan on post in /trip_plans' do
      expect(post: '/trip_plans').to route_to(controller: 'trip_plans', action: 'create', title: 'New Plan', day: '3')
    end
  end
end

现在我需要以某种方式将参数 title: 'New Plan', day: '3' 传递给我的 expect(post: '/trip_plans'),这样看起来就像真正的用户正在填写表格并点击提交。

如何将 POST 请求的参数传递给我的 RSpec 路由规范?

提前致谢!

路由规范通常不会增加太多价值。在路由规范中,您只需测试某个路由是否与正确的控制器匹配。从未实际调用控制器。

相反,您可以使用 控制器规格,用于测试您的应用程序如何响应用户输入:

# spec/controllers/trip_plans_controller_spec.rb
RSpec.describe TripPlansController, type: :controller do

  let(:valid_params) do
    {
        title: 'New Plan',
        day: '3'
    }
  end

  let(:invalid_params) do
    {
        day: 'xxx'
    }
  end

  describe 'POST #create' do

    let(:action) { post :create, valid_params }
    context 'with valid attributes' do
      it 'creates a new post' do
        expect { action }.to change(Post, :count).by(+1)
      end
      it 'has the correct attrributes' do
        action
        expect(assigns(:trip_plan).title).to eq 'New Plan'
        expect(assigns(:trip_plan).day).to eq 3
      end
    end

    context 'with invalid attributes' do
      let(:action) { post :create, invalid_params }

      it 'does not create a new post' do
        expect { action }.to_not change(Post, :count)
      end

      it 'renders the new template' do
        action
        expect(response).to render_template :new
      end
    end
  end
end

功能规范,它们是测试实际用户体验的端到端规范:

RSpec.feature 'Trip Plans' do
  context 'as a User' do
    scenario 'I should be able to create a trip plan' do
      visit root_path
      click_link 'Create a new trip plan'
      fill_in 'Title', with: 'Go west'
      fill_in 'Day', with: 5
      click_button 'Create trip plan'
      expect(page).to have_content 'Trip plan created.'
      expect(page).to have_content 'Go west'
    end
  end
end

控制器规范对于准确测试您的控制器如何响应参数以及您在何处编写对数据库状态的实际期望非常有用。

功能规范很好,因为它们涵盖了您的观点,而且编写良好的规范还保证您的用户路径可以访问。然而,它们通常不会捕获前端不易察觉的错误,而且速度较慢,因为您通常需要呈现多个页面才能进入测试的实际内容。

来自功能规范的堆栈跟踪或错误消息通常不如较低级别的规范有用。

一个好的测试套件通常由模型规范、控制器规范和功能规范组合而成,涵盖了应用程序中最重要的路径。