8

我正在使用Pusher進行Facebook樣式的通知。我已經設置了一個簡單的RSpec測試來測試Pusher是否被觸發。如何使用RSpec測試推送器

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 

回答

0

這可能是一個老問題,但我想補充我的回答。當使用RSpec的Rails應用程序之前測試推,我們寫功能規格如下:

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 

我們還使用假推這對發展和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