ruby-on-rails - 条件代码 if-else 的 Rspec?

标签 ruby-on-rails node.js ruby testing rspec

我是 RSpec 的新手,但在这里我尝试基于此代码创建测试,但我不断收到此错误。有什么建议吗?
代码:

  serialization_scope nil
  before_action :set_list, only: [:show, :destroy, :update]
  before_action :verify_user, only: :show


  def create
    @list = current_user.lists.build(list_params)

    if @list.save

      render json: {message: ['Success']}, status: 200
    else
      render json: {errors:[@list.errors.full_messages]}, status: 400
    end
  end

这是我启动的 RSpec 文件:

require "rails_helper"

RSpec.describe V1::ListsController, :type => :controller do

  describe "POST create" do
    it "returns HTTP status" do
      expect(post :create).to change(@list, :count).by(+1)
      expect(response).to have_http_status :success #200
    end
  end

  describe 'GET status if its not created' do
    it "return HTTP status - reports BAD REQUEST (HTTP status 400)" do
      expect(response.status).to eq 400
    end
  end
end

我得到的错误是:

Failures:

  1) V1::ListsController GET status if its created returns HTTP status
     Failure/Error: expect(post :create).to change(@list, :count).by(+1)
       expected #count to have changed by 1, but was not given a block
     # ./spec/controllers/lists_controller_spec.rb:8:in `block (3 levels) in <top (required)>'

  2) GET status if its not created return HTTP status - reports BAD REQUEST (HTTP status 400)
     Failure/Error: expect(response.status).to eq 400

       expected: 400
            got: 200

       (compared using ==)

最佳答案

试试这段代码。

require 'rails_helper'

RSpec.describe V1::ListsController, type: :request do
  describe 'valid request' do
    it 'returns HTTP status' do
      post '/list', params: { list: { list_name: 'xyz' } }
      expect(response.status).to eq 201
    end
  end
  describe 'invalid request' do
      it "should return unauthorized" do
        post '/list'
        assert_response :unauthorized
      end
    end
end

在参数中你需要传递你的list_params

关于ruby-on-rails - 条件代码 if-else 的 Rspec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47565011/

相关文章:

ruby-on-rails - Rails 自定义消费者 oauth 策略

ruby-on-rails - 使用 Rails 3 在 heroku 上使用 Gmail

ruby-on-rails - rails 与设计 : How to render login page without a layout?

ruby - 如何向后运行 Ruby 函数?

ruby-on-rails - [prometheus, rails]如何在rails服务器上启用prometheus

javascript - 如何在jquery插入的元素上发生 'click'事件?

node.js - ReactJS:从 S3 渲染私有(private)图像资源

node.js - Node JS + Mongodb : ValidationError: User validation failed: username: Path `username` is required

css - 这可能吗?使用 CSS (Stylus) 迭代@keyframes

ruby-on-rails - sidekiq 后台作业发送电子邮件和 heroku worker