2

Can anyone tell me why I'm getting a "no database associated with Sequel::Model" error when trying to run specs in a decoupled rails app? My postgreSQL database has already been created and seeded using Rails (called "quizzy_development").

I have a "lib" directory outside of my rails ("web") app, which includes the following:

"environments.rb":

if ENV['APP_ENV'] == 'development'
  Quizzy.db = Quizzy::SQLDB.new
end

Sequel.connect(:adapter=>'postgres', :host=>'localhost', :database=>'quizzy_development')

"sql.rb":

require 'sequel'

module Quizzy
  class SQLDB
    class Question < Sequel::Model
    end

    def get_questions
    end

    def self.SQLDB
      @__orm_instance ||= SQLDB.new
    end
  end
end

"spec_helper.rb":

require 'pry-byebug'
require './quizzy'

"quizzy.rb":

module Quizzy
  def self.db=(database)
    @__db_instance = database
  end
end

require_relative "./db/sql.rb"
require_relative "./entities/question.rb"
require_relative "./entities/score.rb"
require_relative "./config/environments.rb"

"sql_spec.rb":

require 'spec_helper'

describe Quizzy::SQLDB do
  let(:db) { Quizzy::SQLDB.new }

  it "adds a question" do
  end

  it "gets all questions for a quiz" do
    questions = db.get_questions
  end

end

When I run the "Sequel.connect" code in irb it looks like it's working, but for some reason I'm unable to establish the connection when running through specs. Ideas?

1 Answer 1

1

Here's the solution I found:

Sequel requires that you create a connection before running methods on it, but closes the database connection if it's not in use. Basically, the connection needs to be established whenever you want to call a method. This led to a bit of circular logic in that I was trying to call a method that would (I thought) establish a connection, but since the connection wasn't established I couldn't call the method.

So, one solution is to create a new file, "config.rb", in which the connection is established:

module Quizzy
  def self.SequelConnection
    @sequel_instance ||= Sequel.connect(:adapter=>'postgres', :host=>'localhost', :database=>'quizzy_development')
  end
  Quizzy.SequelConnection
end

The "sql.rb" file is then modified to require the config file and instantiate the connection:

require 'sequel'
require_relative "./config.rb"
module Quizzy
  class SQLDB
    def initialize
      @db = Quizzy.SequelConnection
    end

    class Question < Sequel::Model
    end

    def self.SQLDB
      @__orm_instance ||= SQLDB.new
    end
  end
end

I also removed the Sequel.connect line from "environments.rb".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.