ruby 预期'secure_user.birth_date'已从“1990-01-01”变更为“2000-01-01”,但并未变更

hc2pp10m  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(125)

下面是我的rspec测试代码

require 'rails_helper'

RSpec.describe Users::PaymentController, type: :controller do

  let(:user) { create(:user) }
  let(:secure_user) { create(:secure_user, user_id: user.id, email: 'abc123@mail.com', birth_date: '1990-01-01', gender: 'female', nation: 'jp', prefecture: 'Tokyo-to', municipality: 'Shibuya-ku') }

  describe 'POST #create' do
    params = {
      birth_date: '2000-01-01',
      gender: 'male',
      prefecture: 'Osaka-fu',
      municipality: 'Osaka-shi'
    }
    it "changes secure_user's attributes" do
      expect do
        post :create, params: params
      end.to change{ secure_user.birth_date }.from('1990-01-01').to('2000-01-01')
    end
  end

end

下面是用户::PaymentController中的相关部分

module Users
       class PaymentController < Users::BaseController

         def create
           current_user.secure_user.update(user_personal_info_params)
           ......
           ......
         end

         private

         def user_personal_info_params
           params.permit(:birth_date, :gender, :nation, :prefecture, :municipality)
         end

       end
     end

其逻辑是:在创建payment时添加新信息到current_user.secure_user。但是测试失败,我不知道原因。

1) Users::PaymentController POST #create changes secure_user's attributes
     Failure/Error:
       expect do
         post :create, params: user_info
         binding.pry
       end.to change{ secure_user.birth_date }.from('1990-01-01').to('2000-01-01')

       expected `secure_user.birth_date` to have changed from "1990-01-01" to "2000-01-01", but did not change

我不太熟悉RSpec(英语也不太熟悉),如果有人能帮助我解决这个问题,我将不胜感激。

laawzig2

laawzig21#

尝试使用.reload

...
end.to change{ secure_user.reload.birth_date }.from('1990-01-01').to('2000-01-01')

对象在测试中没有更新,你必须重新加载它,以获得最新的属性。

相关问题