Not able to understand how the method subject! does work

19 views
Skip to first unread message

Arup Rakshit

unread,
Jul 1, 2014, 3:40:39 PM7/1/14
to rs...@googlegroups.com
#######
test.rb
#######

#!/usr/bin/env ruby

class Thing
  def self.count
    @count ||= 0
  end

  def self.count=(val)
    @count += val
  end

  def self.reset_count
    @count = 0
  end

  def initialize
    self.class.count += 1
  end
end

###########
test_spec.rb
###########

require_relative "../test.rb"

describe Thing do
  after(:example) do
    puts "called" 
    #Thing.reset_count
  end

  context "using subject!" do
    subject!(:thing) { Thing.new }

    it "returns 1" do
      expect(Thing.count).to eq(1)
    end

    it "returns 2" do
      expect(Thing.count).to eq(2)
    end
  end
end

If I run the test :-

arup@linux-wzza:~/Ruby> rspec spec/test_spec.rb
.F

Failures:

  1) Thing using subject! returns memoized version on first invocation
     Failure/Error: expect(Thing.count).to eq(1)

       expected: 1
            got: 3

       (compared using ==)
     # ./spec/test_spec.rb:13:in `block (3 levels) in <top (required)>'

Finished in 0.00173 seconds (files took 0.13718 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/test_spec.rb:11 # Thing using subject! returns memoized version on first invocation


Now my question is how @count incremented by 3, shouldn't it be by 2 ?

Surya

unread,
Jul 1, 2014, 4:25:53 PM7/1/14
to rs...@googlegroups.com
I think subject() defines the value which will be returned by the subject method: https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/subject/explicit-subject

context "using subject!" do
    subject { Thing.new }

    it "returns 1" do
      expect(subject.class.count).to eq(1)
    end
end



--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/d1e28613-e751-4b1a-9a9d-79a2ff02e419%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

 Please consider the environment before printing this email.

Regards,
Surya

Aaron Kromer

unread,
Jul 1, 2014, 5:16:25 PM7/1/14
to rs...@googlegroups.com

You have a typo in your Thing code:

  def self.count=(val)
    # Typo is +=, use just =
    @count += val
  end

That should just be @count = val not +=. This is causing count to increase in size each time by 1 plus itself.



Arup Rakshit

unread,
Jul 1, 2014, 10:16:05 PM7/1/14
to rs...@googlegroups.com
Hello Aaron,

Thanks... Late night reading might causes it.. :-) Thanks for your help.
Reply all
Reply to author
Forward
0 new messages