我与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
现在控制器规格失败了:
describe "POST #update" do
context 'when user is signed in' do
let(:user) { Fabricate(:user) }
before { session[:user] = user.id }
context 'with invalid attributes' do
it "does not update the queue items position" do
queue_item1 = Fabricate(:queue_item, user: user, position: 1)
queue_item2 = Fabricate(:queue_item, user: user, position: 2)
post :update_queue, queue_items: [{id: queue_item1.id, position: 6}, {id: queue_item2.id, position: 2.2}]
expect(queue_item1.reload.position).to eq(1)
expect(queue_item2.reload.position).to eq(2)
end
end
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 ==)
我不明白为什么规范会失败但是在浏览器中它会起作用。 我错过了什么?
非常感谢
答案 0 :(得分:2)
我实际上发现了这个问题! 这是由于我在我的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