在 Rails 中创建和测试默认记录

发布于 2024-08-05 12:35:18 字数 477 浏览 0 评论 0原文

我正在为我的网站创建一个用户身份验证系统。我想添加一个默认用户,这样如果我创建一个新站点或重置数据库,我仍然可以登录(并更改默认用户详细信息)。

我在迁移中有以下代码。对于开发数据库来说,一切似乎都工作正常,但在测试时,我添加的默认用户被删除,而是加载了夹具中的数据。有没有办法为此添加单元测试?

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :hashed_password
      t.string :salt

      t.timestamps
    end

    User.add_user("mike", "password")
  end

  def self.down
    drop_table :users
  end
end

I'm creating a user authentication system for my site. I want to add a default user, so that if I create a new site, or reset the database I will still be able to log in (and change the default user details).

I have the code below in the migration. All seems to be working fine for the development database, but when it come to testing the default user I'm adding is removed and the data from the fixture is loaded instead. Is there any way to add unit testing for this?

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :hashed_password
      t.string :salt

      t.timestamps
    end

    User.add_user("mike", "password")
  end

  def self.down
    drop_table :users
  end
end

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

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

发布评论

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

评论(1

苏佲洛 2024-08-12 12:35:18

我强烈建议在 自定义 rake 中执行此类“种子数据”任务,并且在正常的单元测试装置中有不同的数据。

I highly recommend doing this sort of "seed data" inside a custom rake task, and have different data inside normal unit test fixtures.

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