代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

测试在RSpec中具有重定向的请求

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 7 年前

    post

    class PostsController < ApplicationController
      def create
        @post = Post.new(post_params)
    
        if @post.save
          redirect_to @post, notice: 'Post was successfully created.'
        else
          render :new
        end
      end
    end
    

    RSpec.describe 'Posts', type: :request do
      describe 'POST #create' do
        it 'has a 201 response code' do
          post posts_path, params: { post: valid_attributes }
    
          expect(response).to have_http_status(201)
        end
      end
    end
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Vasilisa    7 年前

    如果参数有效,您可以检查是否创建了帖子以及是否重定向了用户。如果在Post模型中有任何验证,最好测试无效参数:

    RSpec.describe 'PostsController', type: :request do
      describe 'POST #create' do
        context 'with valid params' do
          it 'creates a new post' do
            expect { post posts_path, params: { post: valid_attributes } }.to change(Post, :count).by(1)        
            expect(response).to redirect_to post_path(Post.last)
          end
        end
    
        context 'with invalid params' do
          it 'does not create a new post' do
            expect { post posts_path, params: { post: invalid_attributes } }.not_to change(Post, :count)
            expect(response).to have_http_status 200
          end
        end
      end
    end
    
        2
  •  -1
  •   keoghpe    7 年前

    由于帖子创建成功,您的回复代码将为302。在给您的示例代码中,您不会得到201。您可以检查您是否没有收到201

    expect(response).to_not have_http_status(201).