briarheart briarheart - 2 years ago 124
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) }

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 "Test description 1",
completed_at: "Test description 2",

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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download