因为您的问题中没有代码,所以我假设您正在使用minitest-rails并对其进行了正确配置,因为这是我最熟悉的。
假设您有以下代码:
class Authentication < ActiveRecord::Base
def self.find_by_provider_and_uid provider, uid
self.where(provider: provider, uid: uid).first_or_initalize
end
end
此外,我会假设你有以下夹具数据test/fixtures/authentications.yml
test_auth:
provider: twitter
uid: abc123
user: test_user
我将进行类似于以下的测试:
describe Authentication do
describe "find_by_provider_and_uid" do
it "retrieves existing authentication records" do
existing_auth = authentications :test_auth
found_auth = Authentication.find_by_provider_and_uid existing_auth.provider, existing_auth.uid
refute_nil found_auth, "It should return an object"
assert found_auth.persisted?, "The record should have existed previously"
assert_equal existing_auth, found_auth
end
it "creates a new authentication of one doesn't exist" do
new_auth = Authentication.find_by_provider_and_uid "twitter", "IDONTEXIST"
refute_nil new_auth, "It should return an object"
assert new_auth.new_record?, "The record should not have existed previously"
end
end
end
FWIW,我不喜欢这种方法的名称。名称类似于动态查找器,但行为不同。我会将方法重命名为for_provider_and_uid
.