2017-12-22 27 views
1

コールバックbefore_saveモデル起動されていない - 例えば、先頭と末尾の空白ストリップいずれかレールRSPEC /工場ボットは、私はbefore_saveコールバックの数のユーザモデル有する

APP /モデル/ user.rbました:

def strip_whitespace_in_user_names 
    self.first_name.strip! 
    self.first_name.gsub!(" ", "") 
    self.last_name.strip! 
    self.last_name.gsub!(" ", "") 
end 

私は、基本モデルのスペックを持っている、と私は、これは実際に動作することを確認したいと思います。たとえば、 "ネイサン" "ネイサン"

仕様/モデル/ user_spec.rbを返す必要があります。ここでは

RSpec.describe User, type: :model do 
    let(:user) { build :poorly_defined_user } 
    it "has no leading white space" do 
    expect(user.first_name).not_to end_with(" ") 
    end 
end 

はpoorly_defined_userのファクトリの定義である:

require 'faker' 
password = Faker::Internet.password 
# Factory to define a user 
FactoryBot.define do 
    factory :poorly_defined_user, class: User do 
    first_name "  asd " 
    last_name "AS DF " 
    handle "BLASDF824" 
    email Faker::Internet.email 
    password password 
    password_confirmation password 
    end 
end 

しかし、ときに私テストを実行すると、この期待は失敗します。私はpostman(これはAPI用)をチェックし、コールバックは正しく実行され、ユーザーの属性は適切に設定されています。

Rspec/Factory Botが実際にどのように動作するかを反映するために、これがどうして起こっているのか、またはテストを再構築する方法についての助けを借りてください。 create

答えて

2

変更buildのようなので:

let(:user) { create :poorly_defined_user }

buildを呼び出すときのコールバックは発生しませんので、オブジェクトが実際にDBに保存されていません。

+0

完璧に動作します。ご協力いただきありがとうございます。 –

関連する問題