【问题标题】:Trying to write my first Rails View Test in RSpec and failing with instance variable尝试在 RSpec 中编写我的第一个 Rails 视图测试并因实例变量而失败
【发布时间】: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)\”,现在可以了。谢谢!

标签: ruby-on-rails rspec rspec-rails


【解决方案1】:

简单的问题是我没有安装水豚!

【讨论】:

    猜你喜欢
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多