2

Given this class:

class First
  def to_s ; "Hello World" ; end
end

and this spec:

require 'first'

describe First do
  describe "#to_s" do
    it { should == "Hello World" }
  end
end

I get:

Failures:

  1) First#to_s 
     Failure/Error: it { should == "Hello World" }
       expected: "Hello World"
            got: Hello World (using ==)
       Diff:
       @@ -1,2 +1,2 @@
       -"Hello World"
       +Hello World
     # ./spec/first_spec.rb:5:in `block (3 levels) in <top (required)>'

But I would expect this to pass. My questions are:

  • How would a passing spec look like?
  • Why is this spec not passing, specifically?
1
  • About the rails tags: I didn't put them there, because it is actually not a Rails-specific topic. But I won't remove them either, now that they are there, because of the people interested in the topic probably 80% are Rails devs anyway. Commented Mar 20, 2012 at 7:15

2 Answers 2

4

Your outer describe block:

describe First do

sets the subject of the inner examples to be an instance of First. That is, all of the its you're describing will be a First object. The text #to_s example doesn't instruct rspec to call to_s on the object.

Since First.new is not equal to "Hello World" the spec fails.

However, since rspec does call to_s on the object to output it in the failure description, "Hello World" does appear there. You could try the following to ensure that the string conversion is being tested:

its(:to_s) { should == "Hello World" }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Gareth and @apneadiving! Two very good answers, though I prefer this one. In summary: Q1, "How...?" -- The passing spec that I intended uses its (see answer's example) and I can get rid of the inner describe level. Q2, "Why...?" -- I thought using describe "#blah" would set the subject, but that is not the case. Instead, the subject is still First.new.
2

I've never used #method_name to get the result evaluated automatically. I prefer verbosity to be sure of what I'm doing.

Generally, I pick one from these:

describe First do
  specify { First.new.to_s.should == "Hello World" }
end

Or:

describe First do
  describe "#to_s" do
    subject { First.new.to_s }
    it { should == "Hello World" }
  end
end

Or:

describe First do
  describe "#to_s" do
    let(:result) { First.new.to_s }
    specify { result.should == "Hello World" }
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.