Ruby on rails Rspec自定义视图测试
这是我的rspec供查看Ruby on rails Rspec自定义视图测试,ruby-on-rails,ruby-on-rails-4,rspec-rails,Ruby On Rails,Ruby On Rails 4,Rspec Rails,这是我的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
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
这是通知财务总监的费用中的索引
操作。rb
def index
@expense_notifies = ExpenseNotify.all.includes(:user)
end
Failure/Error: <%= expense_notify.user.first_name %> <%=expense_notify.user.last_name%>
ActionView::Template::Error:
undefined method `first_name' for nil:NilClass
这是我的视图index.html.erb
<% @expense_notifies.each do |expense_notify| %>
<%= expense_notify.user.first_name %> <%=expense_notify.user.last_name%>
<%end%>
费用通知.rb
模型
class ExpenseNotify < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
end
class ExpenseNotify
如何通过考试?您应该而不是硬编码分配ID。您永远无法确保数据库中每次运行RSpec时都存在具有特定ID集的对象 而是创建
User
对象并使用User.id
:
require 'rails_helper'
RSpec.describe "expense_notifies/index", type: :view do
let(:user_1) { User.create! }
let(:user_2) { User.create! }
before(:each) do
assign(:expense_notifies, [
ExpenseNotify.create!(user_id: user_1.id),
ExpenseNotify.create!(user_id: user_2.id)
])
end
end
请参阅RSpecs中的使用
另一个建议是,您可以在测试环境中创建
User
和ExpenseNotify
对象。它说,expense\u notify的用户关系为零。请尝试创建用户。用户模型存在,并且有一个用户具有指定的ID 1和2。您可能在错误的环境中运行测试。我看不到您在测试中创建用户。您还可以检查您的测试环境种子。“有一个用户具有指定的ID 1和2。”——@suresh您的错误表明情况正好相反。在运行RSpec时,测试数据库中没有具有这些ID的用户。