5

我是 Rails 和 RSpec 的新手,希望得到一些关于如何让这个测试工作的指示。

我希望从最新到最旧对电子邮件进行排序,但我在测试时遇到了麻烦。

我是 Rails 的新手,到目前为止,让我的测试工作比实际功能更难。

更新

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

这是我得到的错误:

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)>'
4

2 回答 2

8

在您的代码中:

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

Email您正在设定模型应该等于电子邮件数组 的期望。Email是一类。你不能只期望类等于一个数组。可以使用allclass 上的方法找到所有电子邮件Email

您必须将两个数组的期望设置为相等。

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

它应该像这样工作。

于 2013-04-26T21:06:51.613 回答
0

对于较新版本的 RSpec:

let(:emails) { ... }

it 'returns emails in correct order' do
  expect(emails).to eq(['1', '2', '3'])
end
于 2021-03-16T09:20:50.810 回答