我将在问题下方发布所有文件。我对测试非常陌生。我正在尝试为我的应用编写控制器测试。模型是所有权。所有权归团队所有。我正在使用回形针宝石将徽标附加到每个团队。
运行测试时,出现以下错误:
1) Error:
OwnershipsControllerTest#test_Should_retrieve_results:
ActionView::Template::Error: undefined method `logo_file_name' for nil:NilClass
app/views/ownerships/round1.html.erb:23:in `block in _app_views_ownerships_round__html_erb___2932533286089946925_70246915278440'
app/views/ownerships/round1.html.erb:18:in `each'
app/views/ownerships/round1.html.erb:18:in `_app_views_ownerships_round__html_erb___2932533286089946925_70246915278440'
test/controllers/ownership_controller_test.rb:12:in `block in <class:OwnershipsControllerTest>'
它抱怨我如何处理视图中丢失的徽标。这是round1.html.erb中不喜欢的部分:
<% if ownership.team.logo_file_name == nil %>
<td></td>
<% else %>
<td><%= image_tag ownership.team.logo.url(:medium) %></td>
<% end %>
问题不在于回形针附件本身。对Team模型的任何引用都会引发错误。如果删除与徽标相关的代码,则以下内容也会产生相同的错误:
<%= owner.team.name%>
真正令人困惑的是,我对index方法的测试没有引发错误。index和round1视图的代码是相同的!如何设置测试,以便识别关联模型的属性?
owner_controller_test.rb
require 'test_helper'
class OwnershipsControllerTest < ActionController::TestCase
test "Should retrieve index" do
get :index
assert_response :success
end
test "Should retrieve results" do
get :round1
assert_response :success
end
end
所有
one:
round: 1
pick: 1
team_id: 1
player_id: 1
two:
round: 1
pick: 1
team_id: 1
player_id: 1
teams.yml
one:
name: Browns
division: East
logo_file_name: logo.jpg
two:
name: Chargers
division: West
logo_file_name: logo.jpg
楷模
class Ownership < ActiveRecord::Base
belongs_to :player
belongs_to :team
validates :round, :pick, :team_id, presence: true
end
class Team < ActiveRecord::Base
has_many :ownerships
has_many :players, through: :ownerships
validates :name, presence: true
validates :division, presence: true
has_attached_file :logo , :styles => { :small => '10>', :medium => '40>', :large => '60>' }
validates_attachment_content_type :logo, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
owners_controller.rb的相关部分
class OwnershipsController < ApplicationController
def index
@ownerships = Ownership.all.select { |t| t.player_id == nil}
Rails.application.config.counter = (256 - Ownership.all.select{ |t| t.player_id == nil}.count)
end
def round1
@ownerships = Ownership.all.select { |m| m.round == 1}
end
private
def ownership_params
params.require(:ownership).permit(:round,:pick,:team_id,:player_id)
end
您需要在所有权固定装置中添加对团队的引用。您可以按标签引用。
one:
round: 1
pick: 1
team: one
player_id: 1
或者,您当前的方法也可以,只需将主键添加到团队中
所有权
one:
round: 1
pick: 1
team_id: 1
player_id: 1
团队
one:
id: 1
name: Browns
division: East
logo_file_name: logo.jpg
另请参阅:有关灯具关系的更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句