我正在用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测试有误解。
请给我提示。 谢谢。
答案 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,那就没事了require 'rails_helper'
来加载Rails rails_helper
也需要spec_helper
,但事实并非如此rails_helper
的加载速度比spec_helper
慢得多,这是因为它可以引导Rails rails_helper
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