如何设置rails测试中的标题信息和发布数据?

时间:2015-09-29 18:14:21

标签: ruby-on-rails ruby unit-testing actioncontroller wash-out

我正在运行Ruby 1.9.3和Rails 3.1。我可以通过发送自己的XML有效负载来成功手动测试我对Washout gem的使用。我试图在rails测试中重新创建以下bash命令:

curl -H "Content-Type: text/xml; charset=utf-8" -H "SOAPAction:soap_submit_contract" -d@test/fixtures/soap/success.xml http://localhost/soap/action

如您所见,它设置了一些标题数据并将文件发送到文件test/fixtures/soap/success.xml

我在POST中看到的所有其他示例如下所示:

post :parse_pdf,
  :terminal_key => @terminal_key,
  :contract_pdf => load_pdf(pdf)

但在我的情况下,文件数据不是命名参数,而且似乎没有设置标题信息。

如何以与curl命令完全相同的方式提交帖子?

我们的测试套件使用默认的ActionController :: TestCase:

class SoapControllerTest < ActionController::TestCase
  fixtures :terminals

  test "soap_succeeds" do 
    # request.set_header_information ???
    post :action, # file data ???

    assert_match(/success/, @response.body)
  end

end

2 个答案:

答案 0 :(得分:0)

在请求规范中,您可以将headers哈希作为请求方法的第三个参数传递,如下所示:

post :action, {}, {'YOUR_HEADER' => 'value'}

有关详细信息,请参阅documentation

更新

要发布XML数据,请尝试以下方式:

xml_data = File.read('test/fixtures/soap/success.xml')
post :action, xml_data, { 'CONTENT_TYPE' => 'application/xml' }

答案 1 :(得分:0)

在Rails 5中,基于this Gist并具有基于令牌的身份验证,我必须执行以下操作:

# auth_request_helper.rb
module AuthRequestHelper
  def http_login
    @env ||= {}
    User.create!(
      email: 'email', 
      password: 'pass', 
      password_confirmation: 'pass'
      )
     email = 'email'
     password = 'pass'
     # AuthenticateUser is a custom class which logs the user and returns a token
     @env['TOKEN'] = AuthenticateUser.call(user, pw).token
   end
end

然后,在spec文件中:

# users_spec.rb

# login to http basic auth
before(:each) do
  http_login
end

describe 'POST /users' do
  let(:valid_attributes) { 
    { 
      email: 'some_email', 
      password: 'some_pass',
      password_confirmation: 'some_pass',        
      format: :json # Also useful for specifying format
     } 
   }

  context 'when the request is valid' do
    before { post '/users', params: valid_attributes, headers: {'Authorization': @env['TOKEN']} }

    it 'returns status code 201' do
      expect(response).to have_http_status(201) # Success
    end
  end
end