Mar 16
2012
How to simulate a POST request body in a Rails 3 functional test
This was surprisingly underdocumented out in the world. If you've got a Rails controller that ever uses request.body.read, you can set that in a functional test like so:
class ArticlesControllerTest < ActionController::TestCase
test "creates a new article" do
attributes = {
:subject => "10 ways to get traffic by writing blog posts about arcane Rails tips",
:body => "Just kidding, it's totally impossible"
}
@request.env['RAW_POST_DATA'] = attributes.to_json
post(:create)
assert Article.last
end
end
@request is a local variable defined inside of ActionController::TestCase, and used when you make a test request by calling post, get, etc.