我第一次在我的User
模型中尝试自己进行测试,我意识到对于每个测试我都有一个针对user = User.create(:name => "something", :age => 3, :gender => "m")
. 是否有 before_filter 或类似的测试,这样我就不必为每个测试创建一个用户?或者以某种方式将它放在全局命名空间中,以便在任何地方都可以访问它?
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "user is created" do
user = User.create(:name => "Edmund", :age => 3, :gender => "m")
assert_equal user, User.find_by_name("Edmund")
assert_equal 3, User.count
end
test "user has sent messages" do
user = User.create(:name => "Edmund", :age => 3, :gender => "m")
2.times do
user.sent_messages.create(:sender_id => user.id)
end
assert_equal 2, user.sent_messages.count
end
test "user has received messages" do
user = User.create(:name => "Edmund", :age => 3, :gender => "m")
2.times do
user.received_messages.create(:receiver_id => user.id)
end
assert_equal 2, user.received_messages.count
end
end