我有以下 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
我正在尝试测试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
它不起作用的原因是因为在定义类时正在评估方法中的调用,并且在运行测试时我在块中更改了User.current_user
之后的值。should_have_named_scope
current_user
setup
这是我为测试这个 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进行测试呢?