环境:
当我创建rails'mountable引擎'MyEngine'并在'post'模型上生成脚手架时,即使我通过以下步骤修改了功能测试也失败了:
通过以下方式创建可安装的引擎:
$ rails plugin new my_engine --mountable $ cd my_engine $ rake db:create; rake db:migrate; rake db:setup $ rails g scaffold post name zip $ rake db:migrate
'rake test'失败如下:
$ rake test NoMethodError: undefined method `posts' for <MyEngine::PostsControllerTest:0xacd1fa4> ...my_engine/test/functional/my_engine/posts_controller_test.rb:6:in 'block in <class:PostsControllerTest>' ...
根据https://github.com/rails/rails/issues/4971和 http://edgeguides.rubyonrails.org/engines.html“5.1功能测试”, 我修改了两件事:
将以下标志添加到test / test_helper.rb:
class ActiveSupport::TestCase fixtures :all end
自动重新创建测试数据库,因为“无法找到表'my_engine_posts'” 错误发生了:
$(export RAILS_ENV = test; rake db:drop; rake db:create; rake db:migrate; rake db:setup)
将test / functional / my_engine / posts_controller_test.rb修改为:
module MyEngine class PostsControllerTest < ActionController::TestCase setup do @post = my_engine_posts(:one) end ^^^^^^^^^^ ... test "should get index" do get :index, use_route: :my_engine ^^^^^^^^^^^^^^^^^^^^^^^
但是,rake测试仍然无法执行以下步骤:
test_should_create_post(MyEngine :: PostsControllerTest): NoMethodError:未定义的方法`post_path'for ...
其中'post_path'命名路由用于脚手架生成的功能测试。 我认为命名路线看起来不错,因为:
$ rake app:routes my_engine /my_engine MyEngine::Engine Routes for MyEngine::Engine: posts GET /posts(.:format) my_engine/posts#index POST /posts(.:format) my_engine/posts#create new_post GET /posts/new(.:format) my_engine/posts#new edit_post GET /posts/:id/edit(.:format) my_engine/posts#edit post GET /posts/:id(.:format) my_engine/posts#show PUT /posts/:id(.:format) my_engine/posts#update DELETE /posts/:id(.:format) my_engine/posts#destroy
有趣的是,rails app(非插件)脚手架的类似步骤生成功能测试工作(当然!)如下:
$ rails new my_app $ cd my_app/ $ rake db:create; rake db:migrate; rake db:setup $ rails g scaffold post name zip $ rake db:migrate $ rake test
如果有人帮助我如何在可安装的引擎上传递脚手架生成的功能测试,我非常感谢!
答案 0 :(得分:3)
通过将其添加到test/test_helper.rb
:
class ActionController::TestCase
include MyEngine::Engine.routes.url_helpers
end
将MyEngine
更改为您自己的引擎名称。
最初的想法来自http://www.matthewratzloff.com/blog/2011/09/21/testing-routes-with-rails-3-1-engines/#comment-1572
中概述的RSpec解决方案答案 1 :(得分:0)
尝试将这些添加到生成的test_helper.rb:
def post_path(post)
"/my_engine/posts/#{post.to_param}"
end
def posts_path
'/my_engine/posts'
end
它对我有用。