【发布时间】:2025-12-31 00:50:15
【问题描述】:
这是我的视图 rspec
require 'rails_helper'
RSpec.describe "expense_notifies/index", type: :view do
before(:each) do
assign(:expense_notifies, [
ExpenseNotify.create!(:user_id => 1),
ExpenseNotify.create!(:user_id => 2)
])
end
it "renders a list of expense_notifies" do
render
end
end
这是expense_notifies_controller.rb 中的index 操作
def index
@expense_notifies = ExpenseNotify.all.includes(:user)
end
这是我的看法index.html.erb
<% @expense_notifies.each do |expense_notify| %>
<%= expense_notify.user.first_name %> <%=expense_notify.user.last_name%>
<%end%>
每次我运行rspec spec/views/expense_notifies/index.html.erb_spec.rb
Failure/Error: <%= expense_notify.user.first_name %> <%=expense_notify.user.last_name%>
ActionView::Template::Error:
undefined method `first_name' for nil:NilClass
expense_notify.rb 模型
class ExpenseNotify < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
end
如何让测试通过?
【问题讨论】:
-
它说,expense_notify 的用户关系为零。尝试创建用户。
-
用户模型存在,并且有一个指定ids 1和2的用户。
-
您可能在错误的环境中运行测试。我看不到您在测试中创建用户。您还可以检查您的测试环境种子。
-
“有一个指定 id 为 1 和 2 的用户。” - @suresh 你的错误提示相反。在运行 Rspecs 时,您的测试数据库中没有具有这些 ID 的用户。
标签: ruby-on-rails ruby-on-rails-4 rspec-rails