There is often a need to manage and maintain test data during an automated test. There are several ways to store the data, for example in a global variable, a hash or even by creating a class for the data. Classes are usually used when there is other functionality in addition to storing data.

For example, the following class could be implemented for storing information about car models:

class Car
    def initialize(make, model)
        @make   = make
        @model  = model
    end

    def make
        @make
    end

    def make=(make)
        @make = make
    end

    def model
        @model
    end

    def model=(model)
        @model = model
    end
end

The class enables new cars be instantiated and the instance variables accessed with the following method calls:

car = Car.new('Ford', 'Focus')
car.make    # => 'Ford'
car.model   # => 'Focus'
car.make = 'Audi'
car.make        # 'Audi'

The getters and setters can also be created with the attr_accessor method making the same methods to access the data (accessors) to be available:

class Car
    attr_accessor :make, :model
    def initialize(make, model)
        @make   = make
        @model  = model
    end
end

If the class is only used for storing data, other data structures can be used. A shorter way to accomplish the same is by using a Struct:

Car = Struct.new(:make, :model)
car = Car.new('Ford', 'Focus')

car.make    # => 'Ford'
car.model   # => 'Focus'
car.make = 'Audi'
car.make        # => 'Audi'

The same can be accomplished with an OpenStruct, which can be initialised directly with a hash.

require 'ostruct'
car = OpenStruct.new(make: 'Ford', model: 'Focus')

The code above enables the same ways of accessing the attributes as the previous examples.