Rspec after_save

问题描述 投票:0回答:2

我有一个函数检查字符串变量是否为空,如果是,则用一个值填充它。此方法以before_save为前缀。

我想为此写一个rspec测试。我有一个模型工厂,其中的变量是空白的。保存后如何测试变量是否发生变化?

到目前为止,我有,

it 'should autofill country code' do
  empty_country_code = ''
  @store = Factory.build(:store, :country_code => empty_country_code)
  @store.save
  @store.country_code.should eql '1'
end
ruby-on-rails ruby rspec
2个回答
1
投票

我会用这样的东西:

describe 'before_save' do
  let!(:store) { Factory.build(:store, :country_code => '') }

  it 'autofills the country_code' do
    expect { store.save }.to change { store.country_code }.from('').to(1)
  end
end

1
投票

如果要检查数据是否更新到数据库,则应在测试运行到检查点之前再次从数据库获取数据。

例如,如果设置了before_save方法并将country_code更改为1,则可以执行以下操作:

it 'should autofill country code' do
  empty_country_code = '99'
  @store = Factory.build(:store, :country_code => empty_country_code)
  @store.save
  expect(Store.find_by(id: @store.id).country_code).to eq("1")  ## data get from database again
  ## test for more, you can do:
  ## @new_store = Store.find_by(id: @store.id)
  ## @new_store.country_code += 100
  ## @new_store.save
  ## expect(Store.find_by(id: @store.id).country_code).to eq("1")
end

此操作可确保数据库中的数据已刷新。

© www.soinside.com 2019 - 2024. All rights reserved.