[英]Why is my Rails Minitest Polymorphic Failing?
我有以下模型:
class User < ActiveRecord::Base
has_one :setting, as: :resource, dependent: :destroy
has_many :services
end
class Setting < ActiveRecord::Base
belongs_to :resource, polymorphic: true
end
class Service < ActiveRecord::Base
belongs_to :user
end
並且我有一個來自控制器的代碼片段可以訪問它們,在手動測試時可以使用(這是一個before_action方法):
before_action :setup
def get_vars
@setting = Setting.find_by_booking_url @url
@user = @setting.resource
@services = @user.services
end
def setup
@url = params[:url]
@setting = Setting.find_by_url @url
@user = @setting.resource
end
但是,當對這些裝置使用自動測試時:
# fixtures/users.yml
james:
email: 'james@example.com'
first_name: 'James'
last_name: 'Soften'
encrypted_password: <%= default_password_digest %>
# fixtures/settings.yml
scott_settings:
resource: james (User)
time_zone: 'Pacific Time (US & Canada)'
url: 'urlsegment'
和此控制器測試代碼:
setup do
@user = users(:james)
end
def test_booking_page_success
get :new, url: @user.setting.url
assert_response :success
end
它因錯誤而失敗:
undefined method `services` for nil:NilClass
這表示我無法訪問“資源”以從“設置”對象獲取用戶。
我使用byebug(在運行測試的中間)檢查了變量,並且Setting對象(@ user.setting)具有resource_id和resource_name,因此我想知道為什么在以下情況下無法使用“ resource”屬性從Setting對象訪問用戶運行測試。
有任何想法嗎?
謝謝!
編輯:添加了更多的控制器代碼
編輯:在設置夾具中添加了URL字段
在test_booking_page_success之前嘗試以下操作
def test_url
assert_not_empty @user.setting.url
end
您可能傳遞了一個空的'url'參數...如果顯示的固定裝置完整,並且沒有從其他內容生成url。
Upd我能想象的唯一場景是:scott_settings中的booking_url設置為固定裝置中的“ urlsegment”以外的其他值。 因此它返回其他設置為nil的資源...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.