Factorygirl,我无法表达1对1(has_one)与rspec的关联

时间:2016-12-28 09:04:19

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

我想在Decidingscontroller中测试#create,并且Deciding model具有与Undertaking模型相关联的undertaking_id列,并且具有与Asking模型相关联的ask_id列。 所以,我的工厂/ decidings.rb在下面。

    factory :deciding do
       after(:build) do |deciding|
        deciding.asking ||=build(:asking, deciding: deciding)
        deciding.undertaking ||=build(:undertaking, deciding: deciding)
      end
    end

和我的spec / controllers / decidings_controller_spec.rb在下面。

     RSpec.describe DecidingsController, type: :controller do
      describe '#create' do
       before do
         @deciding=build(:deciding)
       end
       context 'correct_user login' do
         before do 
             login_user(@deciding.asking.user)
         end
         it 'creates with deciding +1' do
           expect{post :create , undertaking_id: @deciding.undertaking_id , asking_id: @deciding.asking_id}.to change(Deciding , :count).by(1)
         end
      end
    end
   end

但在这种情况下@deciding在下面。

    #<Deciding id: nil, asking_id: nil, undertaking_id: nil, created_at: nil, updated_at: nil>

所以我无法创建测试,因为undertaking_id和ask_id是零。 为什么undertaking_id和ask_id为零?请帮我... 无论如何,我的工厂/ ask.rb在下面。

   FactoryGirl.define do
    factory :asking do
      association :user
      sequence(:content){|i| "お願いします#{i}"}
   end
  end

1 个答案:

答案 0 :(得分:2)

ID为零,因为记录不会保留。使用build方法时,它不会在数据库中保存记录。如果未保存记录,则它不能具有ID。改为使用create方法。

试试这个:

factory :deciding do
   after(:build) do |deciding|
    deciding.asking ||= create(:asking)
    deciding.undertaking ||= create(:undertaking)
  end
end