【发布时间】:2014-12-24 19:04:20
【问题描述】:
我有这个模型
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
在我的规范中,我尝试这样做
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
但从未通过测试,但始终在远程 api 上创建对象。如果我想查看@user 对象的属性remote_id 的值始终为null。如果我将 build 更改为在工厂中创建,我可以在日志中看到属性已更新,但在测试中使用时它为 null 并且测试失败。
【问题讨论】:
-
我会在 create_in_remote 中打印出响应,看看是否收到响应和响应 ["id"]。我还会在测试中打印出用户对象,并尝试调用 user.reload 以确保它是对象的当前状态。
标签: ruby-on-rails ruby rspec ruby-test