无法通过以下rspec

问题描述 投票:0回答:1
class Admins::Setting < ActiveRecord::Base
  serialize :config
  scope :default_ip,  -> ()  { where(title: 'default-route-ip'.freeze).first }
  scope :term_sbc_ip, -> ()  { where(title: 'term-sbc-ips'.freeze).first }
end

describe 'Admins::Setting' do
   before(:each) do
     Admins::Setting.create(title: 'default-route-ip', config: '192.168.1.65')
     Admins::Setting.create(title: 'term-sbc-ips', config: "[{'192.168.1.79' => '104.197.17.91'},{'192.168.1.42' => '104.196.101.235'}]")
   end 

   describe '#term_sbc_ip' do
     context 'when terminating ip is not present' do
      it 'should return nil' do
        Admins::Setting.term_sbc_ip.destroy
        expect(Admins::Setting.term_sbc_ip).to eq(nil)
      end
    end
  end
end

当我运行以下测试时,我收到以下错误。

Failures:

  1) Admins::Setting#term_sbc_ip when terminating ip is not present should return nil
     Failure/Error: expect(Admins::Setting.term_sbc_ip).to eq(nil)

       expected: nil
            got: #<ActiveRecord::Relation [#<Admins::Setting id: 5, title: "default-route-ip", config: "192.168.1.65", created_at: "2017-12-26 11:38:03", updated_at: "2017-12-26 11:38:03">]>

       (compared using ==)
     # ./spec/models/admins/setting_spec.rb:30:in `block in (root)

请注意为什么当我删除term_sbc_ip记录时,范围会检索default-route-ip对象。

Rspec版本:3.3.2

ActiveRecord的:

  activerecord (4.2.0)

  activerecord-jdbc-adapter (1.3.19)

  activerecord-jdbcpostgresql-adapter (1.3.19)

jruby:9.0.5.0

rails:No its not a rails application

postgres:9.5.9

ruby rspec jruby
1个回答
1
投票

无论你设置scope还是.last,Rails(ActiveRecord)中的.first方法总是返回一个数组(AR集合)。

scope :term_sbc_ip, ->  { where(title: 'term-sbc-ips'.freeze).first }
                                                             ^^^^^# not works

所以你的规格是错的,这是必须写的:

it 'should return an empty array' do
  record = Admins::Setting.term_sbc_ip.first
  record.destroy
  expect(Admins::Setting.term_sbc_ip).to eq([])
end
© www.soinside.com 2019 - 2024. All rights reserved.