← Back to Upcase

Rspec test for database connection?

(Jason Pierce) #1

I am fairly new to TDD and am working on a test for a Ruby backend data process (no Rails here). As a first step I want to test that I can connect to the database. My test (data_export_spec.rb) fails and does not have any value for @db. However, the puts in data_export.rb shows the connection exists and returns an object. Am I missing something from my approach? What should I be doing differently to test an object from the class I am testing?

Thanks in advance for any advice.

from data_export.rb:

class DataExport

  def perform
  def db_connection
    @db = Mysql2::Client.new(:host => 'somewhere', :username => "someone")
    puts @db

from data_export_spec.rb:

RSpec.describe DataExport do
  it 'checks the database connection' do
    data_export = DataExport.new
    puts "db check #{@db}"
    expect(@db).to exist

the error I get:


  1. DataExport checks the database connection
    Failure/Error: expect(@myst_db).to exist
    expected nil to exist but it does not respond to either exist? or exists?

    ./spec/data_export_spec.rb:12:in `block (2 levels) in <top (required)>’

(Andy Waite) #2

@db is an instance variable so isn’t visible outside of the DataExport class. In general, it’s better to test a class via its public interface. In this case it looks like you could just check that #perform returns a non-nil value.