我正在尝试编写涉及使用 Omniauth(特别是 Twitter)登录的集成测试。每当运行 Cucumber 测试时,我得到的错误是:
When I sign in with "Twitter" features/step_definitions/steps.rb:5 undefined method
uid' for #<Hash:0x007fa891f95830> (NoMethodError) ./app/models/user.rb:26:in
from_omniauth' ./app/controllers/omniauth_callbacks_controller.rb:4:inall' ./features/step_definitions/steps.rb:6:in
/^I sign in with "(.*?)"$/' features/user_management.feature:15:in `When I sign in with "Twitter"'
下面是我的用户模型的代码。
def self.from_omniauth(auth)
user = where(twitter_uid: auth.uid).first || check_for_non_twitter_login(auth)
user.twitter_oauth_token = auth.credentials.token
user.twitter_oauth_secret = auth.credentials.secret
user.save! if user.email != ""
user
end
def self.create_from_omniauth(auth)
create do |user|
user.provider = auth.provider
user.twitter_uid = auth.uid
user.twitter_username = auth.info.nickname
user.twitter_oauth_token = auth.credentials.token
user.twitter_oauth_secret = auth.credentials.secret
end
end
我尝试通过将有问题的行更改为来更改访问 uid 值的方式:
user = where(twitter_uid: auth['uid']).first || check_for_non_twitter_login(auth)
这消除了该错误,因此我更改了 auth 哈希中所有提及的数据以使用相同的方法。这破坏了代码在开发中的工作方式(它根本不起作用),然后测试抛出了这个错误:
When I sign in with "Twitter" features/step_definitions/steps.rb:5 undefined method
[]' for nil:NilClass (NoMethodError) ./app/models/user.rb:56:in
block in create_from_omniauth' ./app/models/user.rb:53:increate_from_omniauth' ./app/models/user.rb:38:in
check_for_non_twitter_login' ./app/models/user.rb:26:infrom_omniauth' ./app/controllers/omniauth_callbacks_controller.rb:4:in
all' ./features/step_definitions/steps.rb:6:in/^I sign in with "(.*?)"$/' features/user_management.feature:15:in
When I sign in with "Twitter"'
有人知道我做错了什么吗?
最佳答案
找到了解决办法。而不是使用:
OmniAuth.config.mock_auth ...etc
我用过:
OmniAuth.config.add_mock(:twitter, {"uid" => '12345', "credentials" => {"token" => "mytoken","secret" => "mysecret"} })
现在一切正常。
关于testing - 使用 cucumber 测试 omniauth 登录时没有哈希错误的方法 uid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117141/