ruby-on-rails - 您如何测试依赖于另一个模型的模型?

标签 ruby-on-rails ruby testing rspec associations

我有 UserAccountRole 模型。用户可以单独存在。帐户必须通过角色绑定(bind)到用户。一个帐户必须至少有一个“所有者”类型的角色记录。我不确定如何在 RSpec 和 FactoryGirl 中测试它。

# user_id, account_id, role
Role < ActiveRecord::Base
  belongs_to :user
  belongs_to :account
end

User < ActiveRecord::Base
  has_many :roles
  has_many :accounts, through: roles
  accepts_nested_properties_for :accounts
end

Account < ActiveRecord::Base
  has_many :roles
  has_many :users, through: roles
end

如果用户未登录,Accounts.new 将显示用户和帐户表单。如果用户已登录,则只会显示“帐户”表单。问题是,我不确定在尝试测试关联时 RSpec 中的 Role 和 Account 会是什么样子。

此测试失败(数组返回为空):

describe Account do
  let(:user) { FactoryGirl.create(:user) }
  before { @account = user.accounts.build(title: "ACME Corporation", subdomain: "acme") }
  subject { @account }
  it { should respond_to(:users) }
  its(:users) { should include(user) }

然后,当用户登录时和未登录时,测试会更加复杂。我可以看到类似用例的任何引用示例代码吗?我也不确定要在 roles_spec 中测试什么,以及什么属于 accounts_spec/user_spec。

工厂:

FactoryGirl.define do
  factory :user do
    name                  "Mickey Mouse"
    email                 "mickey@disney.com"
    password              "m1ckey"
    password_confirmation "m1ckey"
  end
  factory :account do
    title     "ACME Corporation"
    subdomain "acme"
  end
  factory :role do
    user
    account
  end
end

最佳答案

您通过使用模拟框架来测试依赖于其他对象的对象 "mock"其他对象。有许多 mock frameworks允许您执行此操作。

关于ruby-on-rails - 您如何测试依赖于另一个模型的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391184/

相关文章:

ruby-on-rails - 同一域下的两个 Rails 应用程序

android - 使用 adb shell 命令测试应用程序,即使其中一个测试失败,如何让它继续?

node.js - 如何构建用于测试的 meteor 应用程序

c# - 通过 C# 测试测试你的数据库

ruby-on-rails - 在开发过程中从 SQLite3 切换到 Postgresql 以适应 Thinking Sphinx

ruby-on-rails - 服务器正在通过 API 端点接收数据,但在创建记录时忽略它 (Rails)

ruby-on-rails - RubyOnRails/从深度嵌套的关系模型构建完整的树

ruby - 使用 Selenium Webdriver 查找 Web 元素

ruby-on-rails - Elasticsearch新手:与Rails和localhost:9200集成

ruby - 通过网络运行 Ruby 脚本