Using RSpec to test for correct order of records in a model

rspec, ruby-on-rails

Solution

In your code:

it "should have the right emails in the right order" do
  Email.should == [@email_newest, @email]
end

You are setting the expectation that the `Email` model should be equal to the array of emails. `Email` is a class. You can't just expect the class to be equal to an array. All emails can be found by using `all` method on class `Email`.

You must set the expectation for two arrays to be equal.

it "should have the right emails in the right order" do
  Email.order('created_at desc').all.should == [@email_newest, @email]
end

It should work like this.

Problem

I'm new to rails and RSpec and would like some pointers on how to get this test to work. I want emails to be sorted from newest to oldest and I'm having trouble testing this. I'm new to Rails and so far I'm having a harder time getting my tests to work then the actual functionality. Updated ``` require 'spec_helper' describe Email do before do @email = Email.new(email_address: "user@example.com") end subject { @email } it { should respond_to(:email_address) } it { should respond_to(:newsletter) } it { should be_valid } describe "order" do @email_newest = Email.new(email_address: "newest@example.com") it "should have the right emails in the right order" do Email.all.should == [@email_newest, @email] end end end ``` Here is the error I get: ``` 1) Email order should have the right emails in the right order Failure/Error: Email.all.should == [@email_newest, @email] expected: [nil, #<Email id: nil, email_address: "user@example.com", newsletter: nil, created_at: nil, updated_at: nil>] got: [] (using ==) Diff: @@ -1,3 +1,2 @@ -[nil, - #<Email id: nil, email_address: "user@example.com", newsletter: nil, created_at: nil, updated_at: nil>] +[] # ./spec/models/email_spec.rb:32:in `block (3 levels) in <top (required)>' ```

Original source