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
答案 0 :(得分: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