问题
I need to receive incoming emails as multipart-formdata via a POST request from Cloudmailin. The POST resembles the following:
Parameters: {"to"=>"<email@exmaple.comt>", "from"=>"whomever@example", "subject"=>"my awesome subject line....
Actually, receiving and parsing emails is super easy because the email is just posted as params: params[:to], params[:from], etc. However, how do I simulate this POST request in rails?
I built a dummy rails app to test out Cloudmailin, so I have an actual request. However, it's a 6k character file, so I'd like to load this file as the parameters of the POST request. I've tried using the built rails post and post_via_redirect methods to load a file, but it escapes all of the parameters( \"to\"), which is no good. Any ideas?
回答1:
So, I ended up doing:
@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"
}
then just:
post "/where_ever", @parameters
seems to get the job done for now
回答2:
A simple way would probably to execute a script in capybara. Just make sure with the @javascript
tag, then load any page in your app that has jQuery installed (technically, you don't need this, but it's much easier. Then:
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
There's the simple post
capybara method too, but I'm not too sure about how that works. Might be worth looking into.
回答3:
I saw this answer last night when I was updating some of my own test code for Rails 3.2.8, and which uses the Mail gem, and thought I'd share what I found. The test code is for an application that needs to take a POST from Cloudmailin and then process it to create a new user with Devise, and then send a confirmation to that user, which the user can then follow to choose a password. Here is my controller spec:
require 'spec_helper'
describe ThankyouByEmailController do
message1 = Mail.new do
from "Frommy McFromerton <frommy.mcfrommerton@gmail.com>"
to "toey.receivesalot@gmail.com"
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
Hope this clean up your own tests. And for anyone else interested in testing the mail gem, mikel's documentation has come a long way for same:
https://github.com/mikel/mail
来源:https://stackoverflow.com/questions/7150444/rspec-capybara-how-to-simulate-incoming-post-requests-rack-test-wont-work