Rails 4:Factory Girl& Rspec与相关模型

时间:2015-06-04 21:13:16

标签: ruby-on-rails ruby rspec tdd factory-bot

我之前修复过一些有问题的代码问题虽然它有点难看。现在的问题是它打破了我的测试!这里的想法是我可以创建一个Campaign并关联1个zip文件和一对多pdf文件。

上一个问题和解决方案: Rails 4.2: Unknown Attribute or Server Error in Log

以下是失败消息:

控制台

  1) CampaignsController POST #create with valid params 
     Failure/Error: post :create, campaign: attributes_for(:campaign)
     ActiveRecord::RecordNotFound:
       Couldn't find Uploadzip with 'id'=
     # ./app/controllers/campaigns_controller.rb:15:in `create'
     # ./spec/controllers/campaigns_controller_spec.rb:36:in `block (4 levels) in <top (required)>'

..以及代码的其余部分。

规格/工厂/ campaigns.rb

FactoryGirl.define do
    factory :campaign do |x|
        x.sequence(:name) { |y| "Rockfest 201#{y} Orange County" }
        x.sequence(:comment) { |y| "Total attendance is #{y}" }
    end
end

规格/控制器/ campaigns_controller.rb

  describe "POST #create" do
    context "with valid params" do
      before(:each) do
        post :create, campaign: attributes_for(:campaign)
      end

      .........

      end

应用/控制器/ campaigns_controller.rb

class CampaignsController < ApplicationController

......................

      def create
        @campaign = Campaign.new(campaign_params)

        if @campaign.save

            zip = Uploadzip.find(params[:uploadzip_id])
            zip.campaign = @campaign
            zip.save

            flash[:success] = "Campaign Successfully Launched!"
            redirect_to @campaign
        else
            ................
        end
      end

.......................

  private

      def campaign_params
        params.require(:campaign).permit(:name, :comment, :campaign_id, uploadpdf_ids: [])
      end

end

这看似简单,我认为是,但我已经尝试退出一些事情,似乎无法让它通过。如何在此测试中支持新的控制器逻辑?任何帮助表示赞赏。

更新

根据zetitic的建议,我创建了以下成功传递的代码。

before(:each) do
  @uploadzip = create(:uploadzip)
  post :create, campaign: attributes_for(:campaign), uploadzip_id: @uploadzip
end

1 个答案:

答案 0 :(得分:3)

uploadedzip_id添加到已发布的参数:

before(:each) do
  post :create, campaign: attributes_for(:campaign), uploadedzip_id: 123456
end