Update record in test db for rspec

25 Views Asked by At

I have a record record with attribute attribute that I want to set to {}, so I've tried

// spec file
record.update_attribute(attribute: {})
record.attribute = {}

// factorybot file
trait :update_attr do
 attribute {{}}
end

But neither has worked when I look for it thru my spec in a script that uses

Record.where(attribute: {})

Because it defaults to having its attribute set. When I print out the record in my spec file, it has the correct attribute, but when I print it out in the script, it has the wrong attribute. I'm not sure where this is being set because I don't see anything in the factory file, but would love to learn how to change the attribute.

Below is example code:

spec file

require 'rails_helper'
require_relative Rails.root.join('script/test.rb')

RSpec.describe FixRecord do
  let(:record) { FactoryBot.create(:record) }

  subject { described_class.call }

  describe 'class#call' do
    before do
      preset.configurations = {}
    end
    it 'fixes record' do
      # this puts will show the record with x id and attribute to be {}
      puts 'record', preset.attribute, record.id
      subject
      expect(preset.attribute).to eq({foo:'bar'})
    end
  end
end

script file

  class ResetError < StandardError; end

  BATCH_SIZE = 1000

  def self.call
    new.call
  end

  def call
    # calling Record.find(x).attribute here return record with filled attribute instead of {}
    binding.pry

    Record.where("attribute=?", "{}") do |record|
      record.update(attribute: {foo: 'bar'})
    end
  end
end

0

There are 0 best solutions below