簡體   English   中英

測試一個模型“屬於”另一個模型

[英]Testing that one model “belongs_to” another model

我有兩個模型-承租人和用戶,每個承租人將有多個用戶,並且我試圖找到一種測試方法來測試創建用戶和自動分配承租人的能力。 當我嘗試運行測試時,出現以下錯誤:

NoMethodError:
  undefined method 'reflect_on_association' for Proc:Class

租戶代碼:

class Tenant < ActiveRecord::Base
attr_accessible :name, :billing_email, :country

validates :name,       :presence => true,
                       :length => { :maximum => 75 },
                       :uniqueness => true

validates :billing_email, :email => true

has_many :users
end

用戶代碼:

class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, :password, :tenant_id

validates :email,       :presence => true,
                        :uniqueness => true,
                        :email => true

validates :first_name,  :presence => true,
                        :length => { :maximum => 50 }

validates :last_name,   :presence => true,
                        :length => { :maximum => 50 }

validate :password_validation

has_many :sessions, :dependent => :destroy
belongs_to :tenant  

end

測試嘗試:

lambda do
  @attr = FactoryGirl.attributes_for(:user)
  post users_path, :user => @attr
  response.should be_success
end.should belong_to(:tenant)

目前尚不清楚您要在這里實現什么。 斷言一個對象“屬於”另一個對象聞起來很不好。 您是否真的在乎為該關聯使用了Emirates_to? 通常,rspec測試最終會在不實際測試任何有用內容的情況下復制被測代碼。

您更有可能希望查看發布到控制器的結果是否產生正確的結果。 既然您沒有向我們展示您的控制器,並且因為我認為RSpec是毫無意義的噪音,那么這就是我要解決的方法。

assert_difference ->{User.count} do
  post: users_path, user: FactoryGirl.attributes_for(:user)
end
# Assuming your users table is cleared before each test..
assert_kind_of Tenant, User.first.tenant

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM