【发布时间】:2018-05-20 01:46:56
【问题描述】:
我想编写一个测试,在删除记录时处理 FOREIGN KEY constraint 错误,但没有引发 ConstraintException。
如下表的架构
class CreateCountries < ActiveRecord::Migration[5.1]
def change
create_table :countries do |t|
t.string :name
t.integer :sequence
end
end
end
class CreateStates < ActiveRecord::Migration[5.1]
def change
create_table :states do |t|
t.string :name
t.integer :sequence
t.references :country, foreign_key: true
end
end
end
我确认在 rails console 中删除它时会引发 ConstraintException。
c = Country.create!(name: 'country')
State.create!(name: 'state', country: c)
c.destroy
(0.1ms) 开始交易 SQL (0.8ms) DELETE FROM "countries" WHERE "countries"."id" = ? [[“身份证”,10]] (6.1ms) 回滚事务 ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY 约束失败:DELETE FROM "countries" WHERE "countries"."id" = ? 来自 /Users/masamoto/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `step'
但是rspec没有出现错误,在我看来是正常删除了。
describe 'Error' do
it 'Destroy' do
country = Country.create!(name: 'hohooho')
State.create!(name: 'oooooo', country: country)
country.destroy
end
end
错误 销毁
在 0.0339 秒内完成(文件加载需要 3.27 秒) 1 个示例,0 次失败
我以为事务没有提交,我尝试设置config.use_transactional_fixtures = false,但没有改变。
我尝试了显式提交,但结果是一样的。
describe 'Error' do
it 'Destroy' do
country = nil
ActiveRecord::Base.transaction do
country = Country.create!(name: 'hohooho')
State.create!(name: 'oooooo', country: country)
end
ActiveRecord::Base.transaction do
country.destroy
end
end
end
有人有想法吗?
【问题讨论】:
标签: ruby-on-rails ruby activerecord rspec exception-handling