RSpec: how to use should_receive on a static method?

rspec, ruby-on-rails

Solution

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

Problem

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 ?

Original source