Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: how to use should_receive on a static method?

I have a module in lib/gcm.rb :

require "net/http"
require "uri"

module GCM
  def self.dispatch_message(reg_ids, data)
    url = URI.parse(GCM_URL + "/send")

    @msg = { :registrationIds => reg_ids, :data => data }

    request = Net::HTTP::Post.new(url.path)
    request.content_type = 'application/json'
    request.body = @msg.to_json
    response = Net::HTTP.start(url.host, url.port) { |http| http.request(request) }
  end
end

I want to test that the dispatch_message is invoked in one of my controllers:

it "should dispatch a GCM message" do
  post :create, :post => @attr, :format => :json
  GCM.should_receive(:dispatch_message)
end

but its failing:

PostsController POST 'create' should dispatch a GCM message
 Failure/Error: GCM.should_receive(:dispatch_message)
   (GCM).dispatch_message(any args)
       expected: 1 time
       received: 0 times

I have disabled network connections with WebMock if it matters.

what am I missing here ?

like image 940
Gal Ben-Haim Avatar asked Dec 06 '25 04:12

Gal Ben-Haim


1 Answers

Your expectation must come before the request is made:

it "should dispatch a GCM message" do
  GCM.should_receive(:dispatch_message)
  post :create, :post => @attr, :format => :json
end
like image 66
Chris Salzberg Avatar answered Dec 08 '25 16:12

Chris Salzberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!