FactoryGirl .update实际上并不更新关联对象

时间:2014-11-14 22:19:05

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

我正在使用Rails 4.1.7,Rspec 3.0.4与FactoryGirl和postgresql ActiveRecord db。

我正在尝试测试找到关联模型的方法,然后更新该模型中的列。此时测试很粗糙,但它正在使所有关联成为必要(我检查了撬)。调用方法时,期望继续返回nil(因为默认情况下列为nil但应更新为日期时间)。以下是代码:

post_picture_spec.rb

require 'rails_helper'

RSpec.describe ModelName::PostPicture, :type => :model do

  describe 'update_campaign method' do

    context 'when the picture is tied to a campaign' do

      before do
        @campaign = FactoryGirl.create(:campaign)
        @campaign.media << @picture1 = FactoryGirl.create(:picture, posted: true, time_scheduled: Date.parse('2014-07-15 18:00:00'), time_posted: Date.parse('2014-07-15 18:00:00'))
        @campaign.media << @picture2 = FactoryGirl.create(:picture, posted: true, time_scheduled: Date.parse('2014-08-20 19:00:00'), time_posted: Date.parse('2014-08-20 19:00:00'))
      end

      it 'should update first item in campaign' do
        # pending("FactoryGirl update issue")
        ModelName::PostPicture.send(:update_campaign, @picture)
        expect(@campaign.time_started).to eq(@picture.time_posted)
      end

  end

end

图片工厂

FactoryGirl.define do
  factory :picture do
    time_approved { Date.parse('2014-08-22 17:00:00') }
    time_posted { Date.parse('2014-08-22 17:00:00') }
    time_scheduled { Date.parse('2014-08-22 17:00:00') }
    processed true
  end
end

post_picture.rb

class ModelName::PostPicture

  def self.call(id)
    [collapsed]
  end

private

      def self.update_campaign(picture)
        campaign = picture.campaign
        campaign_pictures = campaign.pictures.sort_by(&:time_scheduled)
            campaign.update(time_started: picture.time_posted) if campaign_pictures.first == picture
            campaign.update(time_completed: picture.time_posted) if campaign_pictures.last == picture
      end
end

错误:

 Failure/Error: expect(@campaign.time_started).to eq(@picture1.time_posted)

   expected: 2014-07-15 00:00:00.000000000 +0000
        got: nil

   (compared using ==)

2 个答案:

答案 0 :(得分:4)

您的@campaign变量在修改之前已经加载,因此您需要在检查新值之前重新加载它。

it 'should update first item in campaign' do
  ModelName::PostPicture.send(:update_campaign, @picture)
  @campaign.reload
  expect(@campaign.time_started).to eq(@picture.time_posted)
end

答案 1 :(得分:2)

我建议您在广告系列factory_girl中添加图片的关联。我认为问题在于,当您在活动记录对象上使用<<时,实际上并未创建关联。

我会尝试在binding.pry方法中包含pry gem和update_campaign,以查看模型是否正确创建。

顺便说一句,我也会使用let语法而不是before do中的所有内容,只是可重用性。