Rspec:测试模型范围的响应

bo-*_*-oz 0 rspec ruby-on-rails

我正在为模型范围编写一个非常简单的测试:

describe "scope tests" do

  let(:account1) { create(:account, last_seen: Date.today)}
  let(:account2) { create(:account, last_seen: Date.today - 4.days)}
  let(:account3) { create(:account, last_seen: Date.today - 10.days)}
  let(:d) { Date.today}
  let(:seen_between) { Account.seen_between(d - 14.days, d - 2.days) }

  it "response to seen_between" do
    expect(seen_between).to eq([account3, account2])
    expect(seen_between).to_not include(account1)
  end
end
Run Code Online (Sandbox Code Playgroud)

但是我遇到了一些非常冗长的错误:

Failure/Error: expect(Account.all).to eq([account3, account2])

       expected: [#<Account id: 2, date_of_birth: nil, description: nil, active: true, created_at: "2018-05-10 12:05:4..._lead_id: nil, account_category_id: nil, psychiatrisch: nil, oggz: nil, problem: nil, actions: nil>]
            got: #<ActiveRecord::Relation [#<Account id: 3, date_of_birth: nil, description: nil, active: true, create...lead_id: nil, account_category_id: nil, psychiatrisch: nil, oggz: nil, problem: nil, actions: nil>]>
Run Code Online (Sandbox Code Playgroud)

另外,当我将断言的顺序更改为[account2,account3]时,它仍然不起作用。进行此测试的正确方法是什么(假设合并范围确实返回了已经执行的正确记录)

我还尝试了使用inlcudes(),该方法当然有效,但是不检查记录的正确顺序。

谢谢

Pav*_*yuk 5

尝试使用let!#to_amatch_array

let(:today) { Date.today }

let!(:account1) { create(:account, last_seen: today) }
let!(:account2) { create(:account, last_seen: today - 4.days) }
let!(:account3) { create(:account, last_seen: today - 10.days) }

subject { Account.seen_between(today - 14.days, today - 2.days).to_a }

it { is_expected.to match_array [account2, account3] }
Run Code Online (Sandbox Code Playgroud)

PS与match_array你不需要额外的expect(...).not_to include