Where developers come to connect, share, build and be inspired.

4

Use `at` to easily get/set instance variables on an object.

2715 views

At is a small library provides an at method for all Objects which allows you to access instance variables on an object as if they were accessors for testing purposes, usually within test setups and teardowns.

Basically, at directly translates this:

value = user.instance_eval { <a href="/name">@name</a> }
user.instance_eval { <a href="/name">@name</a> = "#{value}!" }

into this:

value = user.at.name
user.at.name = "#{value}!"

Use Case

lib/user.rb

class User

  def initialize(first_name=nil, last_name=nil)
    @first_name, @last_name = first_name, last_name
  end

  def full_name
    [@first_name, @last_name].compact.join(" ")
  end

end

spec/spec_helper.rb

require 'user'
require 'at/setup'

spec/user_spec.rb

describe User do

  describe '#full_name' do

    before :all do
      subject.at.first_name = 'John'
      subject.at.last_name = 'Doe'
    end

    it 'should output the full name correctly' do
      subject.full_name.should == 'John Doe'
    end

  end

end

Comments

Add a comment