如何在 gem 测试中包含 ActiveRecord?

发布于 2024-11-08 14:19:22 字数 1138 浏览 1 评论 0原文

我正在尝试使用 Model < ActiveRecord::Base 在我的 gem 测试之一中,我使用 shoulda 并收到以下错误

./test/model.rb:1:in `require': 没有要加载的文件 -- active_record (LoadError)

如果没有这个调用,我会收到此错误

./test/model.rb:1:未初始化的常量ActiveRecord(NameError)

帮助! 我的测试需要一个准系统 AR 模型:)


my_gem/test/model.rb

require 'active_record' # <= this fails

class Model < ActiveRecord::Base # <= I need a barebones AR model here
  acts_as_flaggable
end

my_gem/test/test_acts_as_flaggable.rb

require 'helper'
require 'model'

class TestActsAsFlaggable < Test::Unit::TestCase
  context "a model" do

    setup do
      @model = Model.new
    end

    should "be able to set flag" do
      @model.flag[:foo] = "bar"
      assert_equal "bar", @model.flag[:foo]
    end

    should "get default value for unset flags" do
      @model = User.new
      assert_equal false, @model.flag[:some_unset_flag]
    end

  end
end

免责声明:我对测试非常陌生。这是我的第一颗宝石,我想确保我以“正确”的方式做事:)

I'm trying to use Model < ActiveRecord::Base in one of my gem tests with shoulda and I'm getting the following error

./test/model.rb:1:in `require': no such file to load -- active_record (LoadError)

Without this call, I'm getting this error

./test/model.rb:1: uninitialized constant ActiveRecord (NameError)

Help! I need a barebones AR model for my tests :)


my_gem/test/model.rb

require 'active_record' # <= this fails

class Model < ActiveRecord::Base # <= I need a barebones AR model here
  acts_as_flaggable
end

my_gem/test/test_acts_as_flaggable.rb

require 'helper'
require 'model'

class TestActsAsFlaggable < Test::Unit::TestCase
  context "a model" do

    setup do
      @model = Model.new
    end

    should "be able to set flag" do
      @model.flag[:foo] = "bar"
      assert_equal "bar", @model.flag[:foo]
    end

    should "get default value for unset flags" do
      @model = User.new
      assert_equal false, @model.flag[:some_unset_flag]
    end

  end
end

Disclaimer: I'm very new to testing. This is my first gem and I wanted to make sure I was doing things the "right" way :)

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

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

发布评论

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

评论(1

疏忽 2024-11-15 14:19:22

如果您想在 Rails 应用程序之外使用它,您还需要 require 'rubygems'

我的 gem 的目标是在 Rails 应用程序内部使用,如果它是您的第一个 gem,我建议使用 enginex 来获得一些时间。诚然,它最初应该帮助制造引擎,但其中包含的测试省去了很多麻烦......

If you want to use it outside of a Rails application, you need to also require 'rubygems'

I the goal of your gem is to be used inside a Rails app, and if it is your first gem, I would recommend using enginex to gain some time. Granted, it's originally supposed to help making engines, but the included testing saves a lot of hassle...

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