A better way to stub out constants

Hi

Something that’s gnawing at me… to avoid using the SQLite3 gem I’m
stubbing it out like this:

 before(:each) do
   @database = mock("SQLite3 database")

   SQLite3 = Module.new
   SQLite3::Database = Class.new
   SQLite3::Database.stub!(:new).and_return(@database)
 end

But then it keeps nagging me:
/spec/celestial/engine/connections/sqlite_connection_spec.rb:14:
warning: already initialized constant SQLite3

Is this the best way to handle simulating a gem? One thought I had
would be to have a section of code that loads the gem and passes the
SQLite3 class in as a variable (more functional style rather than
using global constants). Is this a good idea?

Alternatively, am I better using unless const_defined? to avoid
redefining them, or perhaps silencing errors somehow? Either of
these will still dirty the namespace though.

Better ideas welcome!

Thanks
Ashley


blog @ http://aviewfromafar.net/
linked-in @ http://www.linkedin.com/in/ashleymoran
currently @ home

On 29/10/2007, at 11:27 AM, Ashley M. wrote:

But then it keeps nagging me:
/spec/celestial/engine/connections/sqlite_connection_spec.rb:14:
warning: already initialized constant SQLite3

Similar to my MiddleMan stub … I used

class Object; remove_const :MiddleMan; end

Not sure how kosha it is?

On Oct 31, 2007, at 9:59 pm, Shane M. wrote:

Similar to my MiddleMan stub … I used

class Object; remove_const :MiddleMan; end

Not sure how kosha it is?

Hi Shane

That was my actually my solution in the end, but I didn’t post back to
the list. To be honest, I don’t think anything that messes with the
global namespace is kosha, but I guess it’s something we’ve got to
live with. (You often have to do worse stuff to test Rails, which
makes me feel better.)

I actually summarised the few steps I needed to take on my blog:
<http://aviewfromafar.net/2007/10/31/specifying-dynamic-gem-usage-with-rspec

Quite why I thought it was interesting enough to tell the google bots
but not interesting enough to tell the RSpec list, I don’t know…

Cheers
Ashley


blog @ http://aviewfromafar.net/
linked-in @ http://www.linkedin.com/in/ashleymoran
currently @ home

Nevermind, my bad… the test was perfect… my code was doing something
crazy

I followed this step by step:

Object.class_eval { remove_const :RMovie }

@ffm = mock("RMovie Movie Class")

RMovie = Module.new
RMovie::Movie = Class.new
RMovie::Movie.stub!(:new).and_return(@ffm)

and I got a ‘stack level too deep’ error on the last line. Anyone have
any ideas?