我是 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/