Rspec POST测试未通过。预期响应是< 3XX:重定向>,但是是200

时间:2017-01-17 07:11:39

标签: ruby-on-rails rspec

此POST创建测试无效。它应该重定向到reports_path,但它不起作用。

describe "POST #create" do
    let(:report) { assigns(:report) }
    let(:test_option) { create(:option) }
    let(:test_student) { create(:student) }

    context "when valid" do
      before(:each) do
        post :create, params: {
          report: attributes_for(:report, student: test_student,
          report_options_attributes: [build(:report_option).attributes]
          )
        }
      end

      it "should redirect to reports_path" do
        expect(response).to redirect_to reports_path
      end

我的参数设置如下:

def report_params
    params.require(:report).permit(:student,
      report_options_attributes: [:id, :option, :note, :_destroy]
    )
end

控制器:

def create
    @report = Report.new(report_params)
    if @report.save
      redirect_to reports_path
    else
      render :new
    end
  end

报告模型:

class Report < ApplicationRecord
  belongs_to :student, dependent: :delete
  has_many :report_options, dependent: :destroy

  accepts_nested_attributes_for :report_options, allow_destroy: true
end

ReportOption模型:

class ReportOption < ApplicationRecord
  belongs_to :option
  belongs_to :report, optional: true
end

我在测试中传递了正确的参数,但我真的不知道出了什么问题......

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题。我修复它只是通过params中的id:

def report_params
    params.require(:report).permit(:student_id,
      report_options_attributes: [:id, :option_id, :note, :_destroy]
    )
end

不知道它是否适合你。您还需要将student: test_student更改为student_id: test_student.id内的before(:each)