briarheart briarheart - 7 months ago 40
Ruby Question

Test order in has_many relationship with RSpec

I'm not very experienced with Rails and RSpec and often have troubles with writing tests. So, my next trouble is that I don't know how to test order in model's relationship properly.

Let's say I have simple model like this:

class Kitchen < ActiveRecord::Base
has_many :orders, -> { order(completed_at: :desc) }
end


And simple test for that model:

require 'rails_helper'

RSpec.describe Kitchen, :type => :model do
before { @kitchen = FactoryGirl.create(:kitchen) }

subject { @kitchen }

describe "orders" do
before do
@kitchen.orders.build(description: "Test description 1",
completed_at: 1.day.ago.localtime)

@kitchen.orders.build(description: "Test description 2",
completed_at: Time.now)
end

it "should be sorted by completion date in descending order" do
expect(@kitchen.orders.first.completed_at).to be > @kitchen.orders.last.completed_at
end
end
end


As a result I have got the error:

Failure/Error: expect(@kitchen.orders.first.completed_at).to be > @kitchen.orders.last.completed_at
expected: > Fri, 15 May 2015 12:21:54 UTC +00:00
got: Thu, 14 May 2015 12:21:54 UTC +00:00


Any help will be appreciated.

Answer

You are using build. This does not persist to the database, so when you call @kitchen.orders.first, you are not hitting the database, just getting back the first one you created, which is the wrong one.

Use create instead, then call @kitchen.reload to refresh from the database.