Ruby on rails RSPEC未通过控制器测试(事务),但可在浏览器中工作(rails 4)

Ruby on rails RSPEC未通过控制器测试(事务),但可在浏览器中工作(rails 4),ruby-on-rails,rspec,ruby-on-rails-4,Ruby On Rails,Rspec,Ruby On Rails 4,我对RSPEC有一个奇怪的问题,我无法确定。 测试失败,但当我在浏览器中尝试时,行为按预期工作 以下是迄今为止的模型代码: class QueueItem < ActiveRecord::Base belongs_to :video belongs_to :user validates_presence_of :user_id, :video_id validates_uniqueness_of :video_id, scope: :user_id validates

我对RSPEC有一个奇怪的问题,我无法确定。 测试失败,但当我在浏览器中尝试时,行为按预期工作

以下是迄今为止的模型代码:

class QueueItem < ActiveRecord::Base
  belongs_to :video
  belongs_to :user

  validates_presence_of :user_id, :video_id
  validates_uniqueness_of :video_id, scope: :user_id
  validates_numericality_of :position, only_integer: true

  delegate :category, to: :video
  delegate :title, to: :video, prefix: :video

...

end
class QueueItemsController < ApplicationController

  ...

  before_action :require_user

  def update_queue
    begin
      ActiveRecord::Base.transaction do
        queue_items_params.each do |queue_item_input|
          queue_item = QueueItem.find(queue_item_input[:id])
          queue_item.update!(position: queue_item_input[:position])
        end
      end
    rescue ActiveRecord::RecordInvalid
      flash[:danger] = "Your queue was not updated, make sure you only use numbers to set the position"
      redirect_to queue_items_path
      return
    end
    current_user.queue_items.each_with_index { |queue_item, i| queue_item.update(position: i+1 )}
    redirect_to queue_items_path

  end


  private

  def queue_items_params
    params.permit(queue_items:[:id, :position])[:queue_items]
  end

  ...
end
以及错误消息:

失败:

  1) QueueItemsController POST #update when user is signed in with invalid attributes does not update the queue items position
     Failure/Error: expect(queue_item1.reload.position).to  eq(1)

       expected: 1
            got: 6

       (compared using ==)
我不明白为什么规范失败了,但在浏览器中它可以工作。 我错过了什么


非常感谢

我真的找到了问题! 这是因为我在rspec_helper.rb设置中使用了DatabaseCleaner gem

以下设置不起作用:

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end
我将其更改为:

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :deletion
  end

在我看来,测试中的
2.2
不会引发验证异常。尝试使用此位置值检查记录是否有效
2.2
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :deletion
  end