如何使用具有 after_create 回调的 rspec 测试模型

Ale*_*x S 3 ruby rspec ruby-on-rails ruby-test

我有这个型号

class User < ActiveRecord::Base
  after_create :create_in_remote

  def create_in_remote
   if self.remote_id.nil?
    req_url = "api/create/user/#{self.username}"
    response = Remote.execute_request(req_url)
    if response
      self.update_attribute(:remote_id, response["id"]) if response["id"]
    end
   end
  end
end
Run Code Online (Sandbox Code Playgroud)

在我的规范中我尝试这样做

require 'spec_helper'

describe User do
  before { @user = FactoryGirl.build(:user) }

  subject { @user }


  it "has_remote_id" do
    @user.save! && @user.reload
    expect(@user.remote_id).not_to be_nil
  end
end
Run Code Online (Sandbox Code Playgroud)

但从未通过测试,但对象始终在远程 api 上创建。如果我想查看@user对象的属性remote_id的值始终为null。如果我将构建更改为在工厂中创建,我可以在日志中看到属性已更新,但在测试中使用时它为空并且测试失败。

小智 5

尝试这样做以确保调用回调并期望(user.remote_ip).to eq(...) - 检查remote_ip

describe 'after_create' do
  before { @user = User.new }
  it 'run the create_in_remote callback' do
    expect(@user).to receive(:create_in_remote) 
    @user.run_callbacks(:create) 
  end
end
Run Code Online (Sandbox Code Playgroud)