3

我在 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

我想测试dispatch_message是否在我的一个控制器中调用了:

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

但它失败了:

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

如果重要的话,我已经禁用了与 WebMock 的网络连接。

我在这里想念什么?

4

1 回答 1

11

您的期望必须在提出请求之前出现:

it "should dispatch a GCM message" do
  GCM.should_receive(:dispatch_message)
  post :create, :post => @attr, :format => :json
end
于 2012-10-09T09:54:57.590 回答