【问题标题】:How to make if statement always returns true for Rspec?如何使 if 语句始终为 Rspec 返回 true?
【发布时间】:2025-12-25 10:05:09
【问题描述】:

在我们的 Rails (3.2) 模块之一中,有条件 include

include UsersHelper if find_config_const('allow_sales_manage_customer_login') == 'true'

这里的find_config_const 是一种搜索表以查找allow_sales_manage_customer_login 值的方法。使用 rspec(2.14 版)进行测试时,模块 UserHelper 需要为 include,因此 find_config_const('allow_sales_manage_customer_login') == 'true' 应始终返回 true。 FactoryGirl 在这里不起作用,因为 FactoryGirl 创建的条目是在 includefind_config_const('allow_sales_manage_customer_login') == 'true' 为 false 之后加载的。有没有办法让find_config_const('allow_sales_manage_customer_login') == 'true' 始终为 rspec(2.14 版)返回 true?

【问题讨论】:

    标签: ruby-on-rails-3 rspec


    【解决方案1】:

    答案是使用#stub 或#should_receive 存根方法。

    你能告诉我 find_config_const 方法是在哪里定义的吗?

    假设它是在 SomeHelper 中定义的。你可以这样做:

    SomeHelper.any_instance.stub(:find_config_const).with('allow_sales_manage_customer_login').and_return(true)
    

    【讨论】:

    • @@spiria,find_config_const 在 Authen::AuthenUtility 中定义。我们在 before(:each) 中加入以下内容:Authen::AuthenUtility.any_instance.stub(:find_config_const).with('allow_sales_manage_customer_login').and_return(true)。出现 NoMethod 错误,提示 Authen::AuthenUtility:Module 未定义 any_instance。我们错过了什么?
    • 你能试试这个吗? Authen::AuthenUtility.should_receive(:find_config_const).with('allow_sales_ma‌​nage_customer_login').and_return(true)