【发布时间】:2009-01-21 23:36:12
【问题描述】:
我有以下 ActiveRecord 类:
class User < ActiveRecord::Base
cattr_accessor :current_user
has_many :batch_records
end
class BatchRecord < ActiveRecord::Base
belongs_to :user
named_scope :current_user, lambda {
{ :conditions => { :user_id => User.current_user && User.current_user.id } }
}
end
我正在尝试使用Shoulda 测试named_scope :current_user,但以下不起作用。
class BatchRecordTest < ActiveSupport::TestCase
setup do
User.current_user = Factory(:user)
end
should_have_named_scope :current_user,
:conditions => { :assigned_to_id => User.current_user }
end
它不起作用的原因是因为在定义类时正在评估should_have_named_scope 方法中对User.current_user 的调用,然后我将在current_user 中更改current_user 的值@ 987654329@运行测试时阻塞。
这是我为测试这个 named_scope 所做的:
class BatchRecordTest < ActiveSupport::TestCase
context "with User.current_user set" do
setup do
mock_user = flexmock('user', :id => 1)
flexmock(User).should_receive(:current_user).and_return(mock_user)
end
should_have_named_scope :current_user,
:conditions => { :assigned_to_id => 1 }
end
end
那么您将如何使用 Shoulda 进行测试?
【问题讨论】:
标签: ruby-on-rails ruby unit-testing shoulda