【问题标题】:How to Test Pusher with RSpec如何使用 RSpec 测试 Pusher
【发布时间】:2013-12-07 07:47:29
【问题描述】:

我正在使用 Pusher 进行 facebook 样式通知。我设置了一个简单的 RSpec 测试来测试 Pusher 是否被触发。

scenario "new comment should notify post creator" do
  sign_in_as(user)
  visit user_path(poster)
  fill_in "comment_content", :with => "Great Post!"
  click_button "Submit"

  client = double
  Pusher.stub(:[]).with("User-1").and_return(client)
  client.should_receive(:trigger)
end

此测试通过。但是,如果我使用相同的代码进行另一个测试(两次测试相同的东西),第二个测试不会通过。我是否将第二个测试放在同一个文件或不同的文件中都没关系。我基本上只能测试 Pusher 一次。

第二次测试的错误是……

Failure/Error: client.should_receive(:trigger)
  (Double).trigger(any args)
    expected: 1 time with any arguments
    received: 0 times with any arguments

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec ruby-on-rails-3.2 pusher


    【解决方案1】:

    这可能是一个老问题,但我想添加我的答案。之前在 Rails 应用程序中使用 RSpec 测试 Pusher 时,我们编写了如下功能规范:

    it "user can publish the question" do
      expect_any_instance_of(Pusher::Client).to receive(:trigger)
      visit event_path(event)
      click_on 'Push Question to Audience'
      expect(current_path).to eq  question_path(@question)
      expect(page).to have_content 'Question has been pushed to the audience'
    end
    

    我们还使用了 Pusher Fake,这是一个用于开发和测试的虚假 Pusher 服务器,可在 https://github.com/tristandunn/pusher-fake 获取。

    "运行时,整个假服务在两个随机打开的端口上启动。然后可以在不需要 Pusher 帐户的情况下连接到服务。可以通过检查配置找到套接字和 Web 服务器的主机和端口。”然后,您可以这样做:

    require "rails_helper"
    
    feature "Server triggering a message" do
      before do
        connect
        connect_as "Bob"
      end
    
      scenario "triggers a message on the chat channel", js: true do
        trigger "chat", "message", body: "Hello, world!"
    
        expect(page).to have_content("Hello, world!")
    
        using_session("Bob") do
          expect(page).to have_content("Hello, world!")
        end
      end
    
      protected
    
      def trigger(channel, event, data)
        Pusher.trigger(channel, event, data)
      end
    end
    

    可以在 https://github.com/tristandunn/pusher-fake-example 找到一个示例 repo 来展示这种方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2018-08-23
      • 2019-12-10
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多