问题描述
我创建了一些可以在Rails控制器和视图中使用的gem。我希望能够独立测试宝石。但我一直无法弄清楚如何在gem中创建一个Rails实例来测试这个gem是否可以在Rails应用中使用。
I'm creating some gems that can be used within Rails controllers and views. I'd like to be able to test the gems independently. But I've not been able to figure out how to create an instance of Rails inside the gem to test that the gem will work inside a Rails app.
我非常喜欢使用RSpec,但可能适应Test :: Unit解决方案,或者只是使用Test :: Unit。
I strongly prefer to use RSpec, but could probably adapt a Test::Unit solution, or just use Test::Unit.
我也对Rails插件的类似解决方案感兴趣。
I'd also be interested in similar solutions for Rails plugins.
(我试过谷歌搜索,但是rails gem testing显示我用于测试的宝石,而不是如何测试宝石。已经看过一篇关于这个话题的文章。)
(I tried Googling, but "rails gem testing" shows me gems that are used for testing, not how to test a gem. I'm pretty sure I've seen an article or 2 on this topic.)
推荐答案
看看其他插件(插件和宝石,相同的东西)测试套件。
Take a look at others plugins (plugins and gems, same thing) test suites.
测试增强Active Record的插件非常简单。你可以,所以你在这种情况下所要做的就是将Active Record连接到一个数据库(例如内存中的sqlite数据库)并测试你的codez。
Testing plugins that enhances Active Record is pretty easy. You can use Active Record anywhere, so all you got to do in that case is to connect Active Record to a database (e.g. a in-memory sqlite database) and test your codez.
# test/test_helper.rb
$LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib')
require 'your_thing'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
t.text :excerpt, :body
end
end
class Post < ActiveRecord::Base
validates_presence_of :title
end
# test/my_test.rb
require 'test_helper'
class MyTest < Test::Unit::TestCase
def test_thing
# use Post here
end
end
当您想要测试控制器操作等时,它会变得更加困难。 有一个相当广泛的测试套件,可以模拟出很多东西并让我通过
It gets harder when you want to test controller actions and such. My live validations plugin has a pretty extensive test suite that mocks out lots of things and lets me pass ERb views as a string, you could take a look at that.
将这些Test :: Unit示例调整为RSpec应该是微不足道的,因为它们不会捎带任何东西Test :: Unit。
Adapting these Test::Unit examples to RSpec should be trivial, as they do not piggyback on anything in Test::Unit.
这篇关于在Rails下测试Ruby Gems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!