如何使用 RSpec 测试 Pusher

8

我正在使用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
1个回答

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 找到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接