运行 rspec 时,空表上的 SQLite 约束异常
我的 Rspec 测试套件遇到一个奇怪的问题。将数据插入具有唯一约束的表的所有测试都会失败。通过指定行号单独运行失败的测试可以按预期工作。
为了调查这个问题,我在插入导致约束异常的数据之前打印了该表中的行数,并且报告该表为空。
任何文件中根本没有 before :all
。
我正在使用 DatabaseCleaner,除了这个问题之外,清理似乎正在起作用。
这个例子在运行整个文件时不起作用:
describe User
# ...
describe '#follow_location' do
let(:user) { Factory(:user) }
let(:location) { Factory(:location) }
it 'should raise when trying to follow an already followed location' do
puts LocationFollowship.count # => 0
user.followed_locations << location # exception raised
lambda {
user.follow_location location
}.should raise_error User::AlreadyFollowingLocation
end
end
# …
end
编辑: 我能够追踪到它。它与使用缓存语句的 Rails 有关。调用 ActiveRecord::Base.connection.clear_cache!
使其正常工作。但是在spec_helper.rb中添加此代码片段会导致SQLite异常无法使用封闭语句
。
I'm having a weird problem with my Rspec test suite. All tests that insert data into a table that has a unique constraint fail. Running the failing tests individually by specifying the line number works as expected.
To investigate the issue I printed the number of rows in that table before inserting the data that is causing the constraint exception and it reports that the table is empty.
There is no before :all
in any file at all.
I'm using DatabaseCleaner and, except for this issue, it seems that the cleaning is working.
This e.g. doesn't work when running the whole file:
describe User
# ...
describe '#follow_location' do
let(:user) { Factory(:user) }
let(:location) { Factory(:location) }
it 'should raise when trying to follow an already followed location' do
puts LocationFollowship.count # => 0
user.followed_locations << location # exception raised
lambda {
user.follow_location location
}.should raise_error User::AlreadyFollowingLocation
end
end
# …
end
EDIT:
I was able to track it down. It has to do with Rails using a cached statement. Calling ActiveRecord::Base.connection.clear_cache!
makes it work. But adding this snippet in spec_helper.rb causes an SQLite exception cannot use a closed statement
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我也有这个问题。此外,当我尝试调查时,Ruby 解释器在某些情况下会出现段错误(可能是由 SQLite 引起的)。
我声明了一个唯一索引,如下所示:
向模型添加以下唯一性约束(除了迁移中的现有索引之外)使问题消失:
I had this problem too. In addition, the Ruby interpreter would segfault under certain conditions when I tried to investigate it (probably caused by SQLite).
I have a unique index declared, like so:
Adding the following uniqueness constraint to the model (in addition to the existing index in the migration) made the issue go away: