带有测试单元和活动记录的文章/示例

发布于 2024-10-20 11:14:51 字数 112 浏览 1 评论 0原文

我希望编写一些单元测试,让我像在 Rails 中一样构建/测试非存根 CRUD 函数,但我想使用最少数量的 gem(测试单元和活动记录)。

有人知道任何可能有帮助的资源吗?

谢谢

I'm looking to write some unit tests that will let me build/test non-stubbed CRUD functions like I can in Rails but I want to use a minimal number of gems (test unit&active record).

Anyone know of any resources that might help?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞花火° 2024-10-27 11:14:51

不知道有任何专门与此相关的资源。要让活动记录在简单的测试中工作,您只需要设置连接详细信息和模型类,假设您有一个与活动记录约定匹配的现有数据库可供使用。不知道你处于哪个阶段,但如果你只需要一个简单的例子:

require 'rubygems'
require 'active_record'
require 'test/unit'

ActiveRecord::Base.establish_connection(
  :adapter  => 'sqlite3',
  :database => 'db/my.db'
)

# Assuming a table like:
# CREATE TABLE people (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, age INTEGER NOT NULL);
class Person < ActiveRecord::Base
end

class TestActiveRecord < Test::Unit::TestCase
  def setup
    @bob = Person.create(:name => 'Bob', :age => 95)
  end

  def teardown
    @bob.destroy
  end

  def test_find_bob
    bob = Person.find_by_name('Bob')
    assert_not_nil(bob)
    assert_equal(95, bob.age)
  end
end

除了活动记录本身所依赖的那些之外,这里没有涉及其他宝石。

您必须根据您使用的数据库适配器的类型确定所需的配置设置。如果您的数据库模式不符合活动记录约定,那么您还必须在模型类中指定一些映射。

Don't know of any resources specifically about this. To get active record working in a simple test you would just need to set up the connection details and your model classes assuming you have an existing database to work with that matches the active record conventions. Don't know what stage you are at but if you just need a simple example:

require 'rubygems'
require 'active_record'
require 'test/unit'

ActiveRecord::Base.establish_connection(
  :adapter  => 'sqlite3',
  :database => 'db/my.db'
)

# Assuming a table like:
# CREATE TABLE people (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, age INTEGER NOT NULL);
class Person < ActiveRecord::Base
end

class TestActiveRecord < Test::Unit::TestCase
  def setup
    @bob = Person.create(:name => 'Bob', :age => 95)
  end

  def teardown
    @bob.destroy
  end

  def test_find_bob
    bob = Person.find_by_name('Bob')
    assert_not_nil(bob)
    assert_equal(95, bob.age)
  end
end

There are no other gems involved here other than those that active record itself depends on.

You'll have to work out what configuration settings you need depending on the type of database adapter you are using. If your database schema doesn't conform to the active record conventions then you will also have to specify some mappings in your model classes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文