LaurentBo
LaurentBo

Reputation: 21

Use a double for an instance variable of an object in Rspec

I am a fairly new on Ruby and this is my first question on stackoverflow, so please be patient with me hehe.

I am struggling to pass a Rpec test using a double.

I have a class Plane that has an attr_reader :plane_number from its initialize method @plane_number = plane_number. attr_reader :plane_number

Class Plane   
   def initialize
   @plane_number = plane_number   
   end
end

I use this variable in another class Airport to refer to a specific plane with its plane number in a string message. An example of a string in my code is:

class Airport
  def confirms_landed(plane)
  "The plane #{plane.plane_number} has landed"
  end
end

I created a test with Rspec using a double for the instance of a plane using let(:plane) {double :plane}
But I am not sure how to use a double for the variable plane_number.

describe Airport do
let(:plane) {double :plane}
   it "confirms a plane has landed" do
   subject.confirms_landed(plane)
   expect(subject.confirms_landed(plane)).to eq("The plane #{plane.plane_number} has landed")
   end
end

The code works fine and returns the right string with the plane number in it, however the test fails as I don't assign a double to the variable plane_number (I get this error message : Double :plane received unexpected message :plane_number with (no args))

I am sure this is something very simple to fix but I can't seem to find the right answer.

Upvotes: 0

Views: 3135

Answers (1)

EmuKing
EmuKing

Reputation: 19

From what I can see you're just missing the plane number method on the double

class Airport
  def confirms_landed(plane)
    "The plane #{plane.plane_number} has landed"
  end
end

describe Airport do
  let(:plane) { double(:plane, plane_number: 56) }

  it "confirms a plane has landed" do
      expect(subject.confirms_landed(plane)).to eq("The plane 56 has landed")
  end
end

Upvotes: 1

Related Questions