N
N
Nike02014-06-04 15:29:32
Ruby on Rails
Nike0, 2014-06-04 15:29:32

How to fix error when saving ActiveRecord to spec?

Good afternoon.
Today a specific error appeared: there is a spec test with several examples. Initially, for all contexts in the before :all block, I create common data for the test using FactoryGirl.create() .
In each test case, in one of these objects, 2 fields with the parameters I need are changed and saved using save!
However, everything works fine only for the first test case, on subsequent calls to save! an error:

Mysql2::Error: Duplicate entry '154' for key 'PRIMARY': INSERT INTO `table_name`

Those. for some reason, ActiveRecord considers this record to be new even though it was already created before the tests started. Call in debugger object.new_record? in the before block , :each returns true before the data is changed.
But, if the object was created using Model_name.create!() , then calling new_record? returns false.
Examining the active_record gem didn't answer my question.
Has anyone come across this problem and know the solution?
RoRv. 3.2.18, rspec-railsv. 2.14.0, rubyv. 2.0.0-p451, factory_girl_rails v. 4.2.1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nike0, 2014-06-04
@Nike0

The problem turned out to be much more strange - the following construct is written in spec_helper.rb :

config.around(:each) do |example|
  DatabaseCleaner.cleaning do
    example.run
  end
end

Apparently, after the rollback of one it'a, the state of the object stored in @new_record (ActiveRecord variable) was reset and it was considered new, which caused the error.
UPD. Before all it's in the before :all block (which is not part of the transaction), a record is created and stored in the database. In each of the test cases, we updated and saved this record. After the block was completed, all saved data was rolled back, including the state of the object (new or not), although the record in the database remained, due to which an error occurs with the PRIMARY KEY in the future.
The fix turned out to be quite simple - I left transactions included in spec_helper.rb, but now operated with the object in a different way, without saving it directly (we changed some fields, they were saved in memory, but in the following test cases we continue to work with the record unchanged).
I also tested updating a record via update_column .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question