我会在问题下方发布所有文件。我对测试很陌生。我正在尝试为我的应用程序编写控制器测试。该模型是所有权。所有权归团队所有。我正在使用回形针宝石为每个团队附上徽标。
当我运行测试时,我收到以下错误:
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模型的引用都会引发错误。如果我删除与徽标相关的代码,则以下内容也会生成相同的错误:
&lt;%= ownership.team.name%&gt;
真正令人困惑的是我对index方法的测试没有抛出错误。 index和round1视图的代码是一样的!如何设置测试以便识别相关模型的属性?
ownership_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
ownerships.yml
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
ownerships_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
答案 0 :(得分:1)
您需要在所有权夹具中添加对团队的引用。您可以通过标签引用。
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