RSpec:如何在静态方法上使用should_receive?

时间:2012-10-09 09:49:09

标签: ruby-on-rails rspec

我在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的网络连接。

我在这里错过了什么?

1 个答案:

答案 0 :(得分:11)

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

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