如何用RSpec测试Pusher

tob*_*b88 8 rspec ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 pusher

我正在使用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
Run Code Online (Sandbox Code Playgroud)

这个测试通过.但是,如果我使用相同的代码进行另一次测试(两次测试相同的东西),则第二次测试不会通过.如果我将第二个测试放在同一个文件或不同文件中并不重要.我基本上只能测试一次Pusher.

我在第二次测试中得到的错误是......

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

Ben*_*ker 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
Run Code Online (Sandbox Code Playgroud)

我们还使用了 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
Run Code Online (Sandbox Code Playgroud)

可以在https://github.com/tristandunn/pusher-fake-example找到展示此方法的示例存储库