2011-08-22 165 views
4

我需要通過來自Cloudmailin的POST請求接收傳入的電子郵件,作爲multipart-formdata。該POST類似於以下內容:rspec/capybara:如何模擬傳入的POST請求? (機架測試不起作用)

Parameters: {"to"=>"<[email protected]>", "from"=>"[email protected]", "subject"=>"my awesome subject line.... 

其實,接收並解析郵件是超級容易,因爲郵件僅僅是張貼PARAMS:PARAMS [:對],則params [:從]等。但是,我該怎麼辦在rails中模擬這個POST請求?

我構建了一個虛擬導軌應用程序來測試Cloudmailin,所以我有一個實際的請求。但是,這是一個6k字符的文件,所以我想將這個文件作爲POST請求的參數加載。我嘗試過使用構建的rails post和post_via_redirect方法來加載文件,但它將所有參數(\「轉換爲\」)轉義,這是不好的。有任何想法嗎?

+0

http://railscasts.com/episodes/276-testing-time-web-requests特別https://github.com/chrisk/fakeweb – rubish

+0

謝謝你的評論。我相信fakeweb是爲了測試從外部API獲取。我需要測試傳入的請求。其實,這不是事實。我只需要向控制器發佈一些參數,其餘的測試將確保創建適當的郵件。 – GoodGets

+0

對不起,大概我應該睡了:) – rubish

回答

12

所以,我落得這樣做:。

@parameters = { "x_to_header"=>"<#{ @detail.info }>", 
       "to"=>"<#{ @account.slug }@cloudmailin.net>", 
       "from"=>"#{ @member.email }", 
       "subject"=>"meeting on Monday", 
       "plain"=>"here is my message\nand this is a new line\n\n\nand two new lines\n\n\n\nand a third new line" 
       } 

然後只是:

post "/where_ever", @parameters 

似乎把工作現在

+0

聽起來像一個整潔但簡單的想法 – Vatsala

+0

這將與其他功能(例如'get')一起工作嗎? – Jeff

0

一個簡單的方法可能會在水豚中執行一個腳本。只要確保與@javascript標籤,然後加載在你的應用程序已安裝的jQuery(從技術上說,你不需要任何這頁,但它更容易然後:

When /^I get a post request from Cloudmailin$/ do 
    visit '/some/page/with/jquery' 
    page.execute_script(%{$.post("/some/path?to=some_email&etc=etc");}) 
end 

有簡單post水豚方法太,但我不太確定如何工作可能是值得探討

+0

謝謝拉蒙這個建議。然而,我只是手動建立一個參數散列,然後發佈它的API端點:post'/ incoming',@parameters(我想這是現​​在最簡單的可能的解決方案) – GoodGets

+0

所以你使用capybara的post方法? –

+0

我認爲這只是一個鐵軌瘦? – GoodGets

0

我看到這個答案,昨晚,當我正在更新一些我自己的測試代碼爲Rails 3.2.8進行,並使用郵件的寶石,並認爲我會d分享我發現的內容。測試代碼適用於需要從Cloudmailin獲取POST的應用程序,然後使用Devise對其進行處理以創建新用戶,然後向該用戶發送確認信息,然後用戶可以根據該確認信息選擇密碼。這裏是我的控制器規格:

require 'spec_helper' 

describe ThankyouByEmailController do 

    message1 = Mail.new do 

    from "Frommy McFromerton <[email protected]>" 
    to "[email protected]" 
    subject "cloudmailin test" 
    body 'something' 

    text_part do 
     body 'Here is the attachment you wanted' 
    end 

    html_part do 
     content_type 'text/html; charset=UTF-8' 
     body '<h1>Funky Title</h1><p>Here is the attachment you wanted</p>' 
    end 
    end 

    describe "creating new users" do 

    describe "unregistered FROM sender and Unregistered TO receiver" do 

     it "should create 2 new users" do 
     lambda do 
      post :create, :message => "#{@message1}" 
     end.should change(User, :count).by(2) 
     end 
    end 
    end 
end 

希望這個清理你自己的測試。而對於任何人在測試郵件寶石別的興趣,米克爾的文檔已經走過了很長的路了相同的:

https://github.com/mikel/mail