如何在原始应用中测试狂欢装饰器?

时间:2019-02-20 13:51:03

标签: ruby-on-rails ruby spree

我正在用Spree制作名为“ MyApp”的Rails应用,然后尝试使用RSpec进行测试。

我阅读了Spree Test App Document,并尝试使用RSpec进行测试。

但是我出错了

~/r/d/MyApp ❯❯❯ bundle exec rspec                                                             

An error occurred while loading ./spec/controllers/spree/home_controller_spec.rb.
Failure/Error:
  describe Spree::HomeController, type: :controller do
    it "render index template" do
      get :index
      response.should render_template(:index)
    end
  end

NameError:
  uninitialized constant Spree
# ./spec/controllers/spree/home_controller_spec.rb:3:in `<top (required)>'
No examples found.

Finished in 0.0004 seconds (files took 0.146 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples
  

NameError:未初始化的常量Spree   我认为发生此错误是因为它仅定义装饰器。   原始控制器是在Spree gem(核心,后端,前端...等)中定义的。

详细代码如下:

MyApp / app / controllers / home_controller_decorator.rb

Spree::HomeController.class_eval do
  def index
    do_something
  end
end

MyApp / specs / controllers / home_controller_spec.rb

require 'spec_helper'

describe Spree::HomeController do
  it "render index template" do
    get :index
    response.should render_template(:index)
  end
end

MyApp / spec / spec_helper.rb

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups
  config.disable_monkey_patching!
  config.order = :random
  Kernel.srand config.seed
end

如何测试装饰器的原始逻辑? 我应该在哪里编写代码? 无法测试MyApp / spec目录?

也许我对Spree测试有误解。

请给我提示。 谢谢。

1 个答案:

答案 0 :(得分:1)

问题

它没有加载Rails,所以看不到Spree。

解决方案

MyApp/specs/controllers/home_controller_spec.rb

代替

require 'spec_helper'

describe Spree::HomeController do
  # ...

您需要

require 'rails_helper'

describe Spree::HomeController do
  # ...

更多信息

  • spec_helper旨在设置RSpec,可用于测试普通Ruby对象
  • 如果您要测试的代码位于lib文件夹中并且不依赖于Rails,那就没事了
  • 由于Spree完全依赖于Rails,因此您需要通过require 'rails_helper'来加载Rails
  • rails_helper也需要spec_helper,但事实并非如此
  • rails_helper的加载速度比spec_helper慢得多,这是因为它可以引导Rails

rails_helper

的剖析
  • Rails 5版本
  • 您的rails_helper看起来可能不同
# Load spec_helper
require 'spec_helper'

# Setup Rails to run in test mode
ENV['RAILS_ENV'] ||= 'test'

# This is the magic line that runs Rails. Check out config/environment.rb.
require File.expand_path('../../config/environment', __FILE__)

# Guard against running any tests in production mode
abort("The Rails environment is running in production mode!") if Rails.env.production?

# Load all the rspec rails related goodness
require 'rspec/rails'

# Make sure the migrations are up to date
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end