RSpec, Testing in Ruby — Part 2

The Saga Continues…

Daniel Glover
2 min readJul 22, 2019

As promised, here we have part 2. I’ll be covering how we can set up test variables.

Here We Go

So, for this blog I’ve set up a a test suite that is made to test a class I’ve created called Loginfo. It has a couple class methods that can be evoked, which all return a hash containing organised data, and organised in a specific way.

I want to test each method, making sure that they are created correctly, and contain what I’m expecting them to contain. I also want to test the class itself and also an instance of the class too.

Test Variables

To create a test variable, we first build our describe block for the test variables to be contained to. Before we begin writing our it statements, we declare our test variables. Using test variables are so useful, and not only that, they can help to keep our tests DRY (don’t repeat yourself).

To do this, we use a before statement. Before statements are run before each test and really help to DRY up your test.

To use a before statement we write the statement in before we declare our it statements, like so;

We can then list out the variables we’d require to complete our tests. For my Loginfo class, I need to test two class methods, an instance of the class and the class itself. So I’ll be using 3 test variables. See example;

Notice how I’m prefixing my variable keys with the @ symbol. That’s because these are instance variables, and it’s an instance of this test and makes it available to all methods within the class (or test).

Now, I can use the test variables throughout this test, referencing them like so;

&

Voilà. See you soon, next time I’ll be giving RSpec a break and indulging with something different for a change.

Bye, Bye.

--

--