即使不处于事务模式,rspec也看不到数据库更改

时间:2015-09-26 13:41:49

标签: ruby-on-rails rspec

我的spec_helper中有这个:

config.use_transactional_fixtures = false

config.before(:suite) do
  DatabaseCleaner.clean_with(:truncation)
end

config.before(:each) do
  DatabaseCleaner.strategy = :truncation
  FactoryGirl.reload
end

config.before(:each) do
  DatabaseCleaner.start
end

config.after(:each) do
  Capybara.reset_sessions!
  DatabaseCleaner.clean
end

所以基本上不应该使用任何交易。

我在我的缺席中有这个回调after_save:

ActiveRecord::Base.connection.execute(
%Q[insert into time_checks (user_id, date, minimal_hours)
select users.id, calendar.date, 0 from calendar
inner join users on users.id in (#{user_ids})
where not exists (select * from time_checks where time_checks.user_id = users.id and time_checks.date = calendar.date)
and calendar.date between '#{from}' and '#{to}'])

在进行测试时,它肯定会击中该代码。当我尝试SQL时,它也会在time_checks中插入一些东西。

然而,当我这样做时:

@absence = create(:absence, user: @user, from: "2015-09-10", to: "2015-09-10", hours: 3, category: 0)
Absence.count.should eq(1)
TimeCheck.count.should eq(1)

最后一行是说time_checks中没有记录。为什么会这样?

1 个答案:

答案 0 :(得分:0)

找到原因。插入查询使用日历表。通过运行测试,每次都会截断此表,导致插入不插入任何内容。

解决方案是在截断中排除日历表,如下所示:

excluded_tables = %w[calendar]

config.before(:suite) do
  DatabaseCleaner.clean_with(:truncation, {except: keep_tables})
end

config.before(:each) do
  DatabaseCleaner.strategy = :transaction, {except: keep_tables}
  FactoryGirl.reload
end