【发布时间】:2022-08-21 16:26:45
【问题描述】:
我有一个(仍然)简单的 Rails 书籍应用程序,我想测试一本书的“显示”页面是否包含该书的标题。
show.html.erb 模板仍然非常简单,作为其中的一部分,<%= @book.title %> 被打印出来。 然而,RSpec 在此之前一直在苦苦挣扎。下面是 show.html.erb_spec.rb 的完整代码:
require \'rails_helper\'
RSpec.describe \"books/show.html.erb\", type: :view do
context \'Show page\' do
let(:book) { create(:hobbit) }
end
it \'displays the book title on the show page\' do
assign(:book, book)
render
expect(rendered).to have_content(book.title)
end
end
\"hobbit\" 的工厂如下所示:
FactoryBot.define do
factory :hobbit, class: Book do
title { \'The Hobbit\' }
year { 1937 }
rating { 5 }
condition { 4 }
end
...
end
我得到的错误与规范中的“分配”语句有关。我不明白问题出在哪里 - 显示页面应该知道实例变量@book?
books/show.html.erb
displays the book title on the show page (FAILED - 1)
Failures:
1) books/show.html.erb displays the book title on the show page
Failure/Error: assign(:book, book)
NameError:
undefined local variable or method `book\' for #<RSpec::ExampleGroups::BooksShowHtmlErb \"displays the book title on the show page\" (./spec/views/books/show.html.erb_spec.rb:7)>
# ./spec/views/books/show.html.erb_spec.rb:8:in `block (2 levels) in <top (required)>\'
我确信这是一个非常愚蠢的初学者错误,但我找不到任何可以帮助我解决这个问题的东西?
-
您收到错误是因为您在
context块内定义了book并且it块未嵌套在context下,您应该将it块移动到context块内。 -
天哪,我太愚蠢了。非常感谢您。现在我得到了渲染输出不响应方法“to have_content”的错误 - 错误是“预期的”<a whole lot of html...> to响应“has_content?” '\" ...但更进一步:)
-
我认为
have_content是Capybara的助手,你必须用它来验证->expect(rendered).to match /#{book.title}/ -
是的-我使用了\“to include(book.title)\”,现在可以了。谢谢!
-
尝试在
render :showrelishapp.com/rspec/rspec-rails/v/2-1/docs/view-specs/view-spec 上更改render
标签: ruby-on-rails rspec rspec-rails