vendredi 27 mars 2015

rspec building new record for :has_one STI polymorphic relationship

I am upgrading a project from Rails 3.1/Ruby 1.9.3 to Rails 3.2/Ruby 2.0.0. This involves upgrading rspec from version 2.10 to 2.99 (to being with)


There are relationships set up as follows:



app/models/company.rb
require 'app_permission'
class Company < ActiveRecord::Base
has_one :supervisor_app_permission, class_name: '::SupervisorAppPermission', as: :subject, dependent: :destroy
end





app/models/app_permission.rb
class AppPermission < ActiveRecord::Base
belongs_to :subject, polymorphic: true
.
.
end
class SupervisorAppPermission < AppPermission
.
.
end


Say a company has a supervisor_app_permission in the database, within the rpsec tests any time company.supervisor_app_permission is called the supervisor_app_permission is retrieved from the database but it's being built as a new record, i.e.



company.supervisor_app_permission.new_record? is true


Similarly when updating the attributes of company.supervisor_app_permission:



company.supervisor_app_permission.update_attributes(attr: value)
results in error:
Mysql2::Error: Duplicate entry '1' for key 'PRIMARY': INSERT INTO `app_permissions`......


This only happens within the rspec tests. If I run rails console all works as expected and the code executes as expected within the app too.


Can anyone tell me why the supervisor_app_permission is being built in this within rspec?


Aucun commentaire:

Enregistrer un commentaire