rspec / capybara:如何模拟传入的POST请求? (机架测试不起作用)

我需要通过来自Cloudmailin的POST请求接收传入的电子邮件作为multipart-formdata。 POST类似于以下内容:

Parameters: {"to"=>"", "from"=>"whomever@example", "subject"=>"my awesome subject line.... 

实际上,接收和解析电子邮件非常简单,因为电子邮件只是以params:params [:to],params [:from]等发布。但是,如何在rails中模拟此POST请求?

我构建了一个虚拟rails应用程序来测试Cloudmailin,所以我有一个实际的请求。 但是,它是一个6k字符的文件,所以我想加载这个文件作为POST请求的参数。 我已经尝试使用内置的rails post和post_via_redirect方法来加载文件,但它会转义所有参数(\“to \”),这是不行的。 有任何想法吗?

所以,我最终做了:

 @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 

好像现在已经完成了工作

一种简单的方法可能是在capybara中执行脚本。 只需确保使用@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水豚方法,但我不太确定它是如何工作的。 可能值得研究。

昨晚我在为Rails 3.2.8更新了一些自己的测试代码时看到了这个答案,并使用了Mail gem,并且认为我会分享我发现的内容。 测试代码适用于需要从Cloudmailin接受POST并随后处理它以创建具有Devise的新用户的应用程序,然后向该用户发送确认,然后用户可以按照该用户选择密码。 这是我的控制器规格:

 require 'spec_helper' describe ThankyouByEmailController do message1 = Mail.new do from "Frommy McFromerton " 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 '

Funky Title

Here is the attachment you wanted

' 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

希望这能清理你自己的测试。 对于任何对测试邮件gem感兴趣的人来说,mikel的文档已经走过了漫长的道路:

https://github.com/mikel/mail

Interesting Posts