0

I have a controller function that add columns to table 'custom_fiels'. Columns to add comes from table 'custom_field_descs' I want to test that this function adds all expected columns to the table.

My test look like this :

describe 'GET /update_db' do
  let(:custom_field) { CustomField.create! valid_attributes }

  before :each do
    FactoryBot.create(:custom_field_desc)
    FactoryBot.create(:custom_field_desc, :type_a)
    FactoryBot.create(:custom_field_desc, :type_b)

    custom_field
  end

  after :each do
    # ...
  end

  it 'updates the database with new columns' do
    get custom_fields_update_db_path

    expect(custom_field.reload).to respond_to(:custom_1)
    expect(custom_field).to respond_to(:custom_2)
    expect(custom_field).to respond_to(:custom_3)
    expect(custom_field).to_not respond_to(:custom_4)
    expect(response).to redirect_to(custom_fields_url)
  end
end

The test pass, but I don't know how to remove columns from db after the test. Datas are not removed after this test (the user, the custom field, etc) The next time I throw the test, the columns are already there. and all Tests do not pass because old datas are still in database.

I tried with DatabaseCleaner but it destroy only datas, not created columns. I tried to add ActiveRecord::Base.connection.remove_column :custom_fields, :custom_1 in after:each but it does not delete columns.

Is it the wright way to test this ?

How can I delete the columns from db for the next test ?

Ruby 2.7 Rails 6 RSpec 4

LiKaZ
  • 306
  • 3
  • 9

2 Answers2

0

Slightly hacky, but you can disable schema.rb dump during migrations in test environment

Then, you can just load the untouched schema.rb at RSpec launch (in spec_helper.rb).

Dharman
  • 30,962
  • 25
  • 85
  • 135
Samuel-Zacharie Faure
  • 1,047
  • 11
  • 26
0

normally When we run tests our database cleaned by default after every test, but if your database still have the values please add the following line in your rails_helper.rb file created by Rspec.

config.use_transactional_fixtures = true

and if you have already this line, just make it true.

Humayun Naseer
  • 440
  • 7
  • 18