'RoR rspec with field auto increment
Rails 6
Database PostgresSQL
File migration:
class CreateCategoriesCodeSequence < ActiveRecord::Migration[6.1]
def up
execute <<-SQL
CREATE SEQUENCE categories_code_seq;
SQL
end
def down
execute <<-SQL
DROP SEQUENCE categories_code_seq CASCADE;
SQL
end
end
class AssignSequenceToTableCategories < ActiveRecord::Migration[6.1]
def up
execute <<-SQL
ALERT SEQUENCE categories_code_seq OWNED by categories.code;
ALERT TABLE categories ALTER COLUMN code SET DEFAULT nextval('categories_code_seq');
SQL
end
def down
execute <<-SQL
ALERT SEQUENCE categories_code_seq OWNED by NONE;
SQL
end
end
File FactoryBot:
FactoryBot.define do
factory :category do
sequence(:code) { |number| number }
name { SecureRandom.hex(3) }
end
end
File rspec:
...
let_it_be(:category) { FactoryBot.create(:category) }
let_it_be(:category_1) { FactoryBot.create(:category) }
describe 'POST #create' do
subject do
post_api '/api/v1/categories', params
response
end
let(:params) do
{
name: 'cate_1'
}
end
context 'Test create' do
it {
expect(subject).to have_http_status(:ok)
}
end
end
Controller categories call this function to create new record
def create!(form)
ActiveRecord::Base.transaction do
Category.create!(from)
end
end
When I add rescue in function create!, I see error duplicate code field.
Field code is unique
FactoryBot sequence not map with nextval('categories_code_seq').
When I add a test post create new category, I get respond error 500. Because code is duplicate.
Maybe nextval('categories_code_seq') don't increase follow FactoryBot sequence.
How can create case test with postgresql sequence field?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

