我正在使用MiniTest框架,并希望编写模型测试。这是我的测试代码:
it "must find or create authentication" do
auth = Authentication.find_by_provider_and_uid( @auth.provider,
@auth.uid )
val = auth.nil?
if val==true
Authentication.create_with_omniauth @auth
end
end
此测试检查Authentication.find_by_provider_and_uid
方法是否存在,如果auth
为零,则会创建新的auth
。
我是用if
条款写的,但我不知道它是否属实。我该如何纠正这个测试?
答案 0 :(得分:1)
由于您的问题中没有代码,我将假设您正在使用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
。