I am using rpsec to assert that a certain method generates the expected query:
describe '.customers' do
let(:segment) { create(:segment) }
let!(:rule1) do
Rule.create!(segment: segment, filter_key: 'generic',
attr_name: 'first_name', operator: '=', values: ['john'])
end
let!(:rule2) do
Rule.create!(segment: segment, filter_key: 'generic',
attr_name: 'orders_count', operator: '>=', values: ['3'])
end
let(:actual_query) { segment.customers.to_sql }
let(:expected_query) do
Customer
.where('first_name = john')
.where('orders_count >= 3')
.to_sql
end
it 'applies all the rules scopes to customer' do
expect(actual_query).to eq(expected_query)
end
end
It usually passes, the thing is that sometimes (for some reason) the where clauses in one of the sql queries get reordered so, since the to_sql is actually the string of the query to execute, sometimes it fails saying:
Failure/Error: expect(actual_query).to eq(expected_query)
expected: "SELECT \"customers\".* FROM \"customers\" WHERE (orders_count >= '3') AND (first_name = 'john')" got: "SELECT \"customers\".* FROM \"customers\" WHERE (first_name = 'john') AND (orders_count >= '3')" (compared using ==)
when they are actually the same in terms of the execution. Any ideas on how else to assert the two queries are the same without having to add test customers to compare the queries after they executed?