[英]Testing Rails ActiveRecord before_create method with Rspec
[英]How to test before_create method with Rspec in rails 4
在我的用戶模型中,我具有一個為用戶生成帳戶ID的功能。 我想編寫一個創建用戶的測試(我正在使用FactoryGirl),然后檢查以確保保存用戶后account_id字段不為空。 在我目前的測試中,我收到一條錯誤消息,內容如下:
NoMethodError: undefined method `to_not=' for #<RSpec>
user.rb
class User < ActiveRecord::Base
before_create :generate_account_id
private
def generate_account_id
self.account_id = loop do
random_account_id = rand.to_s[2..6]
break random_account_id unless self.class.exists?(account_id: random_account_id)
end
end
end
user_spec.rb
#spec/models/user_spec.rb
require 'spec_helper'
require 'rails_helper'
describe User do
it "has a valid factory" do
user = create(:user, :user)
expect(user).to be_valid
end
it "receives a Account ID on successful create" do
user = FactoryGirl.build(:user)
expect(user.account_id).to_not == nil
end
end
您的錯誤是由於輸入錯誤造成的:“未定義的方法”表示您正在調用不存在的內容。 在這種情況下,Ruby將您的.to_not ==
調用解釋為分配嘗試。 如果查看RSpec文檔中的==
,則會發現它也使用be
方法:
expect(user.account_id).to_not be == nil
另外,如果使用be_nil
匹配器 ,則測試可能會更清晰:
expect(user.account_id).to_not be_nil
這個問題的另一方面是您使用的是build
而不是create
。 與ActiveRecord一樣, FactoryGirl的生成方法 (請參見“使用工廠”一節)不會保存對象。 結果,將不會觸發before_create
回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.