RSpec测试:将多个参数发布到方法中

时间:2016-04-16 15:17:30

标签: ruby-on-rails ruby rspec

我正在使用RSpec测试我的Rails 4应用程序,我想发布一个"多个选择" PARAM。 params方法是这样的:

  def general_mailing_params
    params.require(:mailing).permit({:receivers => []}, :subject, :content)
  end

正如您所看到的receivers参数是多重选择,如何在RSpec测试中发布此类参数?

1 个答案:

答案 0 :(得分:3)

在RSpec控制器和请求规范中,您可以简单地传递数组和散列来创建任何给定的参数散列。

控制器(功能)规范:

require 'rails_helper'
describe MailingsController do

  let!(:receiver) { create(:receiver) }

  describe 'POST :create' do
    it "has the correct receivers" do
      post :create, { mailing: { receivers: [receiver.id] } }
      expect(Post.last.receivers).to eq [receiver]
    end
  end
end

请求(集成)规范:

require 'rails_helper'
describe 'Mailings' do
  let!(:receiver) { create(:receiver) }
  describe 'POST /mailings' do
    it "has the correct receivers" do
      post '/mailings', { mailing: { receivers: [receiver.id] } }
      expect(Post.last.receivers).to eq [receiver]
    end
  end
end

但是请注意,如果您正在使用诸如collection_checkboxes之类的rails集合助手,则param键应为receiver_ids