0
如果我通過運行rspec spec/controllers/brands_controller_spec.rb來運行以下規範,則最後一次測試會失敗,告訴我用戶不在數據庫中的PG錯誤。但是,如果我單獨運行測試,它們都會通過,所以它看起來不像我的測試搞砸了,只是我缺少rspec的東西?Rspec控制器 - 當我運行單個測試時工作,但不是文件中的所有測試?
我每次更新用戶時都會創建一個活動,當用戶創建並登錄(Devise記錄登錄日期等)時會觸發該活動,從而創建活動。當我的測試日誌中的管理員用戶試圖創建與管理員用戶關聯的活動時,錯誤是說,即使我登錄用戶,我違反了PG規則,因爲用戶不在數據庫中。雖然它是?很困惑。
品牌控制器規格
describe 'GET #index' do
context 'unauthenticated_user' do
it "blocks an unauthenticated_user from getting to the index page" do
get :index
expect(response).to redirect_to new_user_session_path
end
end
context 'authenticated_user NOT admin' do
it "redirects non admin employees" do
login_user
get :index
expect(response).to redirect_to @user
end
end
context 'authenticated_user admin' do
it "renders the index template for the authenticated_user" do
login_admin
get :index
expect(response).to render_template :index
end
end
end
規格/支持/ controller_macros.rb
module ControllerMacros
def login_user
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = FactoryGirl.create(:user)
sign_in @user
end
def login_admin
@request.env["devise.mapping"] = Devise.mappings[:user]
@admin_user = FactoryGirl.create(:admin)
sign_in @admin_user
end
end
錯誤:
1) BrandsController GET #index authenticated_user admin renders the index template for the authenticated_user
Failure/Error: Activity.create(user_id: user_id, trackable_id: self.id, trackable_type: self.class.name, action: "#{self.class.name} #{self.id} #{self.full_name} created")
ActiveRecord::InvalidForeignKey:
PG::ForeignKeyViolation: ERROR: insert or update on table "activities" violates foreign key constraint "fk_rails_7e11bb717f"
DETAIL: Key (user_id)=(2185) is not present in table "users".
: INSERT INTO "activities" ("user_id", "trackable_id", "trackable_type", "action", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"
# ./app/models/user.rb:691:in `record_create'
# ./spec/support/controller_macros.rb:10:in `login_admin'
# ./spec/controllers/brands_controller_spec.rb:26:in `block (4 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# PG::ForeignKeyViolation:
# ERROR: insert or update on table "activities" violates foreign key constraint "fk_rails_7e11bb717f"
# DETAIL: Key (user_id)=(2185) is not present in table "users".
# ./app/models/user.rb:691:in `record_create'
編輯: 添加我發現用撬測試中另一個錯誤。
它似乎與PG阻止用戶創建在第二次測試中通過實際創建用戶。
ActiveRecord::StatementInvalid:
PG::InFailedSqlTransaction: ERROR:
current transaction is aborted, commands ignored until end of transaction block
: SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
編輯添加在數據庫清理東西:
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
config.after(:each) do
DatabaseCleaner.clean
end
可以肯定的是,'user'和'''工廠工作?檢查創建的用戶是否有效。 –
是的,這是有效的。他們是有效的,如果我單獨運行這個測試真的很奇怪,它們都可以工作。只有當我嘗試運行文件中的所有測試時,它們纔會失敗。 –
您是否使用了一些數據庫清理和'before_save'回調來跟蹤活動(用戶創建的)? –