How to stub a method called in configuration block in sinatra application?

143 views Asked by At

As per sinatra documentation, we use configure block to run something once at startup. http://sinatrarb.com/intro.html

Consider, the below configure where I am fetching the credentials using Creds class and setting to creds.

configure do
    # setting at startup
    set :creds, Creds.fetch_creds
  end

While writing the unit tests using mocha, how can I stub this fetch_creds method? Please guide.

2

There are 2 answers

0
m26a On

You can do that:

Creds.stubs(:fetch_creds)

https://github.com/freerange/mocha/#usage

0
tee_zed_0 On

I assume you have something like this in your tests, somewhere before requests calls:

let(:app) { AppName.new } 

So first of all you need to inject your code before you initialize your app instance.

I am going with something like this:

  let(:app_class) { Class.new(AppName) } # for clean object definition
  let(:app) { app_class.new }

Then, where you need it:

 let(:app_class) { super().instance_exec { set :my_var, 'value' } }

Now, all code evaluated in current RSpec context will have your var.