我有“一个客户有很多书”的联想。
我没有显示书籍的索引视图,而是client_id => 1
对其进行了编辑以显示客户的姓名;它有效,但测试表明不同。
我正在尝试使用示例客户端和书籍为测试数据库播种,但我似乎无法使其正常工作。
你能看出我哪里错了吗?
我认为这与“nil:NilClass”有关。
规范/视图/书籍/index.html.erb_spec.rb
require 'spec_helper'
describe "books/index" do
before(:each) do
assign(:clients, [
stub_model(Client,
:name => "Name",
:email => "Email Address",
)
])
assign(:books, [
stub_model(Book,
:title => "Title",
:client_id => 1
)
])
end
it "renders a list of books" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "tr>td", :text => "Title".to_s, :count => 2
assert_select "tr>td", :text => 1.to_s, :count => 2
end
end
应用程序/模型/book.rb
class Book < ActiveRecord::Base
belongs_to :client
attr_accessible :title, :client_id
validates :title, presence: true
end
应用程序/模型/client.rb
class Client < ActiveRecord::Base
has_many :books
attr_accessible :name, :email
before_save { |user| user.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
应用程序/控制器/books_controller.rb(片段)
class BooksController < ApplicationController
# GET /books
# GET /books.json
def index
@books = Book.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @books }
end
end
end
app/views/books/index.html.erb
<h1>Listing books</h1>
<table>
<tr>
<th>Title</th>
<th>Client Name</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.client.name %></td>
<td><%= link_to 'Show', book %></td>
<td><%= link_to 'Edit', edit_book_path(book) %></td>
<td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Book', new_book_path %>
测试输出
1) books/index renders a list of books
Failure/Error: render
ActionView::Template::Error:
undefined method `name' for nil:NilClass
# ./app/views/books/index.html.erb:15:in `_app_views_books_index_html_erb__##########_#####'
# ./app/views/books/index.html.erb:12:in `_app_views_books_index_html_erb__##########_#####'
# ./spec/views/books/index.html.erb_spec.rb:20:in `(root)'
使用工厂
如果改为使用 FactoryGirl,我会收到类似的错误“nil:NilClass 的未定义方法 'each'”。
规范/视图/书籍/index.html.erb_spec.rb
require 'spec_helper'
describe "books/index" do
before do
FactoryGirl.create(:book)
end
it "renders a list of books" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "tr>td", :text => "Title".to_s, :count => 2
assert_select "tr>td", :text => 1.to_s, :count => 2
end
end
测试输出
1) books/index renders a list of books
Failure/Error: render
ActionView::Template::Error:
undefined method `each' for nil:NilClass
# ./app/views/books/index.html.erb:12:in `_app_views_books_index_html_erb___##########_#####'
# ./spec/views/books/index.html.erb_spec.rb:9:in `(root)'