ruby-on-rails 测试在单独运行时成功,在所有测试的常规运行时不成功

xuo3flqw  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(147)

我有一个单独的测试通过,但是当我一起运行所有东西时,它失败了。我运行了--bisect标志,这是它给我的:

The minimal reproduction command is:
  rspec ./spec/requests/api/v1/categories_requests_spec.rb[1:3:1] ./spec/requests/api/v1/categorizations_requests_spec.rb[1:1:1]

字符串
下面是这些块的代码:
spec/requests/API/v1/categories_requests_spec.rb[1:3:1]

describe 'DELETE api/v1/categories/:id' do
    let!(:category) { create :category }
    let(:params) { { id: category.id } }

    subject { delete api_v1_category_path(params) }

    it 'delete category' do
      expect { subject }.to change { Category.count }.by(-1)
      expect(response).to have_http_status(200)
    end
  end


和spec/requests/API/v1/categorizations_requests_spec.rb[1:1:1]

RSpec.describe 'Api::V1::Categorizations', type: :request do
  let(:category) { create :category }
  let(:product) { create :product }

  describe 'POST api/v1/categorizations' do
    let(:params) { { category_id: category.id, product_id: product.id } }
    subject { post api_v1_categorizations_path, params: params }

    it 'create categorization' do
      expect { subject }.to change { Categorization.count }.by(1)
      expect(response).to have_http_status(201)
    end

    context 'does not create a new categorization if it already exists' do
      let!(:categorization) do
        create :categorization, category: category, product: product
      end

      it 'does not create categorization' do
        expect { subject }.not_to(change { Categorization.count })
        expect(response).to have_http_status(422)
      end
    end
  end



老实说,我不知道他到底没有从数据库中删除什么,为什么会发生冲突。(我输出fabricate-categories标识符到终端),但一切正常。请帮助我,我不明白问题是什么,这些测试用例是如何相互干扰的?
失败文本案例本身的消息:

Failures:

  1) Api::V1::Categorizations POST api/v1/categorizations create categorization
     Failure/Error: expect { subject }.to change { Categorization.count }.by(1)
       expected `Categorization.count` to have changed by 1, but was changed by 0
     # ./spec/requests/api/v1/categorizations_requests_spec.rb:15:in `block (3 levels) in <main>'
     # ./spec/spec_helper.rb:100:in `block (3 levels) in <top (required)>'
     # ./spec/spec_helper.rb:99:in `block (2 levels) in <top (required)>'

nszi6y05

nszi6y051#

决定了!我不完全理解实际发生了什么,但错误是在我的控制器中,product变量存储了category ID,category变量存储了product ID。

class Api::V1::CategorizationsController < Api::V1::BaseController
  # POST api/v1/categorizations
  def create
    @product = Category.find(params[:category_id])
    @category = Product.find(params[:product_id])
    @categorization = Categorization.create(category_id: @category.id, product_id: @product.id)
    if @categorization.save
      render jsonapi: @categorization, status: :created, code: '201'
    else
      render jsonapi_errors: @categorization.errors,
             status: :unprocessable_entity, code: '422'
    end
  end
end

字符串
但我还是不明白为什么单独运行的测试是成功的。

相关问题