Ruby on rails 为什么在我的RSPEC测试中没有对一个对象调用这个函数?
我有以下Ruby on rails 为什么在我的RSPEC测试中没有对一个对象调用这个函数?,ruby-on-rails,rspec,ruby-on-rails-5,rspec-rails,Ruby On Rails,Rspec,Ruby On Rails 5,Rspec Rails,我有以下PositionGroup型号: # == Schema Information # # Table name: position_groups # # id :bigint not null, primary key # ticker :string # total_spend :float # total_units :integer #
PositionGroup
型号:
# == Schema Information
#
# Table name: position_groups
#
# id :bigint not null, primary key
# ticker :string
# total_spend :float
# total_units :integer
# total_value :float
# created_at :datetime not null
# updated_at :datetime not null
# portfolio_id :integer
#
class PositionGroup < ApplicationRecord
has_many :positions
belongs_to :portfolio
before_save :update_total_units
def update_total_units
self.positions.each do |p|
self.total_units = p.volume + self.total_units
end
end
end
然而,当我运行它时,它在第一次测试中点击了binding.pry
,它显示pg.total_units
未设置
49: it "should calculate the total # of units" do
50: # (Position 1 Volume + Position 2 Volume)
51: # 100 + 100 = 200
=> 52: binding.pry
53: expect(pg.total_units).to eql 200
54: end
55:
[1] pry(#<RSpec::ExampleGroups::PositionGroup::Methods>)> pg
=> #<PositionGroup:0x00007fd63d4e41c8
id: 2,
ticker: nil,
portfolio_id: 4,
created_at: Tue, 17 Mar 2020 08:05:42 UTC +00:00,
updated_at: Tue, 17 Mar 2020 08:05:42 UTC +00:00,
total_units: nil,
total_spend: nil,
total_value: nil,
[2] pry(#<RSpec::ExampleGroups::PositionGroup::Methods>)> pg.positions.count
=> 2
[4] pry(#<RSpec::ExampleGroups::PositionGroup::Methods>)> pg.total_units
=> nil
Rails
有许多
添加在模型上保存回调之前不会调用
您可以在关联上添加
回调之前使用。例如,类似这样的内容:
class PositionGroup
医生在这里:我试过了,但也没用。对于该测试,我得到了一个不同的错误错误数量的参数(给定1,预期为0)
。这更好,但现在我得到了另一个错误:NoMethodError:undefined method'+,for nil:NilClass
,我是否应该将total\u units
设置为default:0
?@marcamillion Yes integer列应始终默认为0
。
49: it "should calculate the total # of units" do
50: # (Position 1 Volume + Position 2 Volume)
51: # 100 + 100 = 200
=> 52: binding.pry
53: expect(pg.total_units).to eql 200
54: end
55:
[1] pry(#<RSpec::ExampleGroups::PositionGroup::Methods>)> pg
=> #<PositionGroup:0x00007fd63d4e41c8
id: 2,
ticker: nil,
portfolio_id: 4,
created_at: Tue, 17 Mar 2020 08:05:42 UTC +00:00,
updated_at: Tue, 17 Mar 2020 08:05:42 UTC +00:00,
total_units: nil,
total_spend: nil,
total_value: nil,
[2] pry(#<RSpec::ExampleGroups::PositionGroup::Methods>)> pg.positions.count
=> 2
[4] pry(#<RSpec::ExampleGroups::PositionGroup::Methods>)> pg.total_units
=> nil
let(:position1) { create(:position, stock: stock, portfolio: portfolio, position_group: pg)}