#StackBounty: #ruby-on-rails #rspec Rspec let variable producing weird result

Bounty: 100

I am having a weird issue with RSpec that I don’t quite understand.

This is my port_stock_spec.rb file:

# == Schema Information
#
# Table name: port_stocks
#
#  id                :bigint(8)        not null, primary key
#  portfolio_id      :integer
#  stock_id          :integer
#  volume            :integer
#  transaction_price :float
#  current_price     :float
#  percent_change    :float
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  current_value     :float
#  dollar_change     :float
#  total_spend       :float
#  transaction_date  :datetime
#  action            :integer
#  position          :integer          default("open")
#  ticker            :string
#  slug              :string
#

require 'rails_helper'

RSpec.describe PortStock, type: :model do
  let(:stock) { create(:stock, price: 10.00) }
  let(:portfolio) { create(:portfolio) }
  let(:port_stock_1) { create(:port_stock, stock: stock, portfolio: portfolio, transaction_price: stock.price, action: :buy, volume: 100) }

  context "associations" do
    it { should belong_to(:portfolio) }
    it { should belong_to (:stock) }
  end

  context "methods" do
    it "should accurately calculate the positive percent_change of the current PortStock" do
      port_stock_1.current_price = 20.00
      expect(port_stock_1.calculate_percent_change).to eql 100.00
    end

    it "should accurately calculate the negative percent_change of the current PortStock" do
      port_stock_1.current_price = 5.00
      expect(port_stock_1.calculate_percent_change).to eql(-50.00)
    end

    it "should accurately calculate the negative dollar_change of the current PortStock" do
      port_stock_1.current_price = 5.00
      port_stock_1.volume = 1000
      expect(port_stock_1.calculate_dollar_change).to eql (-5000.00)
    end

    # more specs that may or may no interact with the let variables.            

    it "should accurately calculate the portfolio's initial_dollar_value" do
      expect(portfolio.initial_dollar_value).to eql 1000.00
    end

end

Then I have the following method on my portfolio.rb model:

  def calculate_portfolio_initial_dollar_value
    if self.portfolio.initial_dollar_value.nil?
      self.portfolio.initial_dollar_value = 0.0
    end
    self.portfolio.initial_dollar_value += (self.transaction_price * self.volume)
    self.portfolio.save!
  end

When I run my test suite, that last test keeps failing, when it shouldn’t:

Failures:

  1) PortStock methods should accurately calculate the portfolio's initial_dollar_value
     Failure/Error: expect(portfolio.initial_dollar_value).to eql 1000.00

       expected: 1000.0
            got: 798229.0

       (compared using eql?)
     # ./spec/models/port_stock_spec.rb:77:in `block (3 levels) in <top (required)>'

Finished in 5.05 seconds (files took 3.68 seconds to load)
29 examples, 1 failure, 19 pending

So I put a binding.pry within the it blocks of the last few tests and when I check the portfolio.initial_dollar_value it repeatedly changes the value.

[1] pry(#<RSpec::ExampleGroups::PortStock::Methods>)> portfolio
=> #<Portfolio:0x00007fcdc5c5db28
 id: 14,
 user_id: 7,
 current_dollar_value: 2864770.0,
 percent_change: 75.02,
 created_at: Sat, 13 Apr 2019 00:36:24 UTC +00:00,
 updated_at: Sat, 13 Apr 2019 00:36:24 UTC +00:00,
 num_winners: 2,
 num_losers: 7,
 initial_dollar_value: 860679.0,
 dollar_change: 92865.0>
[2] pry(#<RSpec::ExampleGroups::PortStock::Methods>)> port_stock_1.portfolio
=> #<Portfolio:0x00007fcdc5c5db28
 id: 14,
 user_id: 7,
 current_dollar_value: 150.0,
 percent_change: -85.0,
 created_at: Sat, 13 Apr 2019 00:36:24 UTC +00:00,
 updated_at: Sat, 13 Apr 2019 00:36:42 UTC +00:00,
 num_winners: 0,
 num_losers: 1,
 initial_dollar_value: 1000.0,
 dollar_change: -850.0>
[3] pry(#<RSpec::ExampleGroups::PortStock::Methods>)> portfolio
=> #<Portfolio:0x00007fcdc5c5db28
 id: 14,
 user_id: 7,
 current_dollar_value: 150.0,
 percent_change: -85.0,
 created_at: Sat, 13 Apr 2019 00:36:24 UTC +00:00,
 updated_at: Sat, 13 Apr 2019 00:36:42 UTC +00:00,
 num_winners: 0,
 num_losers: 1,
 initial_dollar_value: 1000.0,
 dollar_change: -850.0>
[4] pry(#<RSpec::ExampleGroups::PortStock::Methods>)> portfolio
=> #<Portfolio:0x00007fcdc5c5db28
 id: 14,
 user_id: 7,
 current_dollar_value: 150.0,
 percent_change: -85.0,
 created_at: Sat, 13 Apr 2019 00:36:24 UTC +00:00,
 updated_at: Sat, 13 Apr 2019 00:36:42 UTC +00:00,
 num_winners: 0,
 num_losers: 1,
 initial_dollar_value: 1000.0,
 dollar_change: -850.0>
[5] pry(#<RSpec::ExampleGroups::PortStock::Methods>)> 

I don’t understand why.

Thoughts?

Edit 1

This is portfolio.rb Factory:

FactoryBot.define do
  factory :portfolio do
    user
    current_dollar_value { Faker::Number.number(7) }
    percent_change { Faker::Number.decimal(2) }
    num_winners { Faker::Number.number(1) }
    num_losers { Faker::Number.number(1) }
    initial_dollar_value { Faker::Number.number(6) }
    dollar_change { Faker::Number.number(5) }
  end
end

Edit 2

There is a callback on my port_stock.rb model that triggers methods related to portfolio_initial_dollar_value:

after_save :calculate_portfolio_initial_dollar_value

Also other callbacks that impact other aspects of the portfolio:

  after_save :update_portfolio_current_dollar_value
  after_save :update_portfolio_initial_dollar_value, if: (:total_spend_previously_changed? || :volume_previously_changed?)

  def update_portfolio_current_dollar_value
    self.portfolio.current_dollar_value = self.portfolio.port_stocks.open.map(&:current_value).sum
    self.portfolio.save!
  end

  def update_portfolio_initial_dollar_value
    self.portfolio.initial_dollar_value = self.portfolio.port_stocks.open.map { |ps| ps.volume * ps.transaction_price }.sum
    self.portfolio.save!
  end

Edit 3

For the full version both the model (port_stock.rb) & spec (port_stock_spec.rb) files, check out this gist. I didn’t want to pollute SO with that full dump.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.