Lesson Weekend

Before we start writing programs that use databases, we need to think a bit about how databases work so that we can avoid a couple pitfalls.

In the last section, we learned how to clear class variables between tests like this:

describe(Thing) do
  before() do
    Thing.clear()
  end
...

We don't want this to happen when we use a database, though. The whole point of a database is to save information. When we run our specs, it shouldn't delete all the data from our program. At the same time, we don't want data being saved between tests. As we saw in the last section, this will make our specs fail in unexpected ways.

The solution to this problem is actually very simple. We need to have two databases for every project:

  • One for our test environment;
  • One for our development environment.
  • If our application were active, we'd also have a production environment, but we won't worry about that right now.

This means we can clear our test database after each spec without affecting development or production databases.

We'll also need to override the equality operator just like we did in the last course section. Often we'll grab information from a database and then use it to instantiate a new object. If we repeat that process at different times, we usually want to treat those objects as equivalent. But they aren't equivalent by default.

Fortunately, we can do this exactly like we did in the last section. For example, we might have a method like this to make sure that both objects have the same class and name:

def ==(other)
  self.class.eql?(other.class) & self.name.eql?(other.name)
end

One thing to note: we should always be very careful when overriding Ruby's built-in methods. It's usually not a good idea because it can lead to unexpected behavior in your application. In this case, we need to override == to test our methods.

With that, we're ready to start using databases in our apps.

Overview


You need to create two databases: one for tests and one for development.

Create a Class#== method to override the existing Class#== method so that you can compare two objects that are exactly the same in our eyes, but are different to the computer.

def ==(other)
  same_class = self.class().eql?(other.class())
  same_name = self.name().eql?(other.name())
  same_class.&(same_name)
end

Lesson 5 of 29
Last updated August 7, 2022