RSpec路由规范POST请求问题

时间:2015-07-04 12:57:10

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

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

我的路线是这样的:

dt2                 t
1968-10-23 12:45:37 12:45:37

所以我有一条像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

现在我需要以某种方式将params 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',这样看起来真正的用户正在填写表单并点击提交。

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

您可以使用的是控制器规范,它们用于测试您的应用程序如何响应用户输入:

# 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

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

功能规格很不错,因为它们也可以覆盖您的视图,而且编写良好的规范也可以保证您的用户路径可以访问。然而,它们通常不会捕获从前端不易察觉的错误并且速度较慢,因为您经常需要渲染几页以达到测试的实际效果。

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

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