简体   繁体   中英

Connecting to MySQL DB in Ruby Rspec

[n00b alert] I'm probably doing this all wrong... RSpec outputs this failure:

1)...                                       #skipped irrelevant info
   Failure/Error: graph.read_db('example1')
   Not connected to any DB.                 #error msg
   #./prim.rb:135:in 'read_db'
   #./prim_spec.rb:171:in 'block (2 levels) in <top (required)>'

I have set up a MySQL database on the same machine. The program provides an algorithm for computing a graph's minimum spanning tree. Has methods for file I/O, database I/O using ActiveRecord, etc. All WORKS WELL except RSpec tests. Code (irrelevant parts left out):

prim_spec.rb

describe PGraph, "online" do
    before (:all) do
        ActiveRecord::Base.establish_connection(
        :adapter => "mysql2",
        :host => "localhost",
        :username => "root",
        :password => "xxxxx",
        :database => "rubytasks" )
        #the exact same statement works perfectly when running the program itself, but fails in RSpec
    end
    before (:each) do
        @graph = PGraph.new
    end

    it "should correctly retrieve data from database" do
        @graph.read_db('example1')   #line 171
        #business part goes here
    end
end

prim.rb

class PGraph
    def read_db(graphID)
        #the error which is raised (line 135):
        raise "Not connected to any DB." unless ActiveRecord::Base.connected?
        #reading goes here
    end
end

Connection and PGraph manipulation is performed in ui.rb. So, ummm, what's the correct way to access a real DB (I'm lazy) for testing (or is the problem elsewhere?)? Preferably something simple, since this is just a school assignment. And without messing with Rails or other gems. PS: I'm using the most recent versions of all gems and server. On Windows 7 x86. Ruby 1.9.2. Thanks.

I'm guessing not everything is loaded properly when you run your rspec tests. Are all classes that setup your database connection loaded properly and with the right parameters when running rspec?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM