[英]RSPEC fails controller test (transaction) but works in the browser (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_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 ==)
我不明白為什么規范失敗但在瀏覽器中它工作。 我錯過了什么?
非常感謝你
我實際上發現了這個問題! 這是由於我在我的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.