【问题标题】:Testing that one model "belongs_to" another model测试一个模型“属于”另一个模型
【发布时间】:2012-03-21 13:11:55
【问题描述】:

我有两个模型 - 租户和用户,每个租户将有_many 用户,我正在尝试找到一种方法来测试创建用户和自动分配租户的能力。当我尝试运行测试时,出现以下错误:

NoMethodError:
  undefined method 'reflect_on_association' for Proc:Class

租户代码:

class Tenant < ActiveRecord::Base
attr_accessible :name, :billing_email, :country

validates :name,       :presence => true,
                       :length => { :maximum => 75 },
                       :uniqueness => true

validates :billing_email, :email => true

has_many :users
end

用户代码:

class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, :password, :tenant_id

validates :email,       :presence => true,
                        :uniqueness => true,
                        :email => true

validates :first_name,  :presence => true,
                        :length => { :maximum => 50 }

validates :last_name,   :presence => true,
                        :length => { :maximum => 50 }

validate :password_validation

has_many :sessions, :dependent => :destroy
belongs_to :tenant  

end

测试尝试:

lambda do
  @attr = FactoryGirl.attributes_for(:user)
  post users_path, :user => @attr
  response.should be_success
end.should belong_to(:tenant)

【问题讨论】:

  • 您的测试毫无意义 - lambda 对象不属于任何东西。除此之外,作为一个非 rspec 用户,我看不到像 belong_to(:tenant) 这样的东西的意义。找到新用户并断言其租户是 X 有什么问题?
  • 嗨 noodl,我想这基本上就是我想要做的,但我想我是以错误的方式去做。有没有更简单的方法可以做到这一点,因为我不知道 lambda 是错误的方法,我是 Rails 新手,我的测试工作基于教程示例

标签: ruby-on-rails ruby-on-rails-3 rspec rspec2 belongs-to


【解决方案1】:

目前还不清楚您要在这里实现什么。断言一个对象“属于”另一个对象闻起来很糟糕。你真的在乎belongs_to 被用于关联吗?似乎很多时候 rspec 测试最终会复制被测代码而没有实际测试任何有用的东西。

您更有可能有兴趣查看 POST 到您的控制器的结果是否会产生正确的结果。由于您没有向我们展示您的控制器,而且我认为 RSpec 是毫无意义的噪音,所以我将如何解决这个问题..

assert_difference ->{User.count} do
  post: users_path, user: FactoryGirl.attributes_for(:user)
end
# Assuming your users table is cleared before each test..
assert_kind_of Tenant, User.first.tenant

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多