【问题标题】:Rspec - obvious test is failing, how to troubleshoot?Rspec - 明显的测试失败,如何排除故障?
【发布时间】:2014-04-22 00:30:21
【问题描述】:

我有一个非常简单的应用程序,我正在尝试使用 rspec 进行测试。我很难确定是我的配置有问题,还是代码有问题。 /people/index.html.erb 的第一行是<h1>Totally Awesome Page</h1>

错误:

expected to find text "Totally Awesome Page" in "Index"
./spec/features/people_spec.rb:19:in `block (3 levels) in <class:PeopleSpec>'

测试宝石:

group :development, :test do
  gem 'rspec'
  gem 'rspec-rails'
  gem 'capybara'
  gem 'factory_girl_rails'
end

spec/features/people_spec.rb:

require 'spec_helper'

class PeopleSpec < ActionDispatch::IntegrationTest

  describe "People" do

    describe "Index" do

     before { visit '/people'}

      it { should have_content('Totally Awesome Page')}

    end
  end
end

spec/spec_helper:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'minitest/autorun'
require 'capybara/rails'
require 'capybara/rspec'

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.use_transactional_fixtures = true

  config.infer_base_class_for_anonymous_controllers = false

  config.order = "random"
  config.include Capybara::DSL
end

路线:

people_path     GET     /people(.:format)   people#index
              POST  /people(.:format)   people#create
new_person_path     GET     /people/new(.:format)   people#new
edit_person_pathGET     /people/:id/edit(.:format)  people#edit
person_path     GET     /people/:id(.:format)   people#show
              PATCH     /people/:id(.:format)   people#update
              PUT   /people/:id(.:format)   people#update
              DELETE    /people/:id(.:format)   people#destroy 

【问题讨论】:

  • 检查launchy gem。这种规格真是太棒了。
  • 为该路径显示rake routes

标签: ruby-on-rails rspec capybara


【解决方案1】:

添加gem 'launchy',然后您可以在visit 之后使用save_and_open_page 来查看渲染页面的样子。

subject { page } 添加到规范中以修复它。

如果您说it,则它必须指向某些东西。在你的测试中它没有。 你可以在page 上使用should 来做到这一点(page 不是你可以测试的唯一一个。还有更多,比如response 甚至 lambdas)这样:

it "some description" do
  page.should have_content('foo')
end

或者,如果您对page 有很多测试,那么您可以用简短的方式编写它们:

it { should have_content('foo') }

但您需要先为it 指定主题:

subject { page }

【讨论】:

  • 我可以用这个命令启动页面。正确的页面以“Totally Awesome Page”作为标题显示。
  • 添加subject { page }
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2018-10-23
  • 2021-07-02
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多