Hermetic Testing with Rspec - Part 3

Expect the Initializer to Take a Color Attribute





require 'rails_helper'


RSpec.describe Pencil, type: :model do

 subject {Pencil.new}


 describe "initialize" do

  it "should create a pencil" do

   expect(subject).to be_a(Pencil)

  end

   

  describe "with a custom initializer" do

   subject {Pencil.new(color: "red")}


   it "should have a color attribute that can be defined in the initializer" do

    expect(subject.color).to eq("red")

   end

  end

 end


 describe "#set_color" do

  before(:each) do

   subject.set_color("red")

  end


  it "should have a color attribute that can be set" do

   expect(subject.color).to eq("red")

  end

 end

end


class Pencil

 attr_accessor :color


 def initialize(* args)

  @color = args[0][:color] if args[0] # a passive initializer (silently fails of no color)

 end


 def set_color(color)

  @color = color

 end

end