【问题标题】:mock Rails.env.development? using rspec模拟 Rails.env.development?使用 rspec
【发布时间】:2014-02-04 21:08:24
【问题描述】:

我正在使用 rspec 编写单元测试。

我想模拟 Rails.env.develepment?返回真。我怎样才能做到这一点?。

我试过了

Rails.env.stub(:development?, nil).and_return(true)

它会抛出这个错误

activesupport-4.0.0/lib/active_support/string_inquirer.rb:22:in `method_missing': undefined method `any_instance' for "test":ActiveSupport::StringInquirer (NoMethodError)

更新 红宝石版本 ruby​​-2.0.0-p353, 轨道 4.0.0, rspec 2.11

describe "welcome_signup" do
    let(:mail) { Notifier.welcome_signup user }

    describe "in dev mode" do
      Rails.env.stub(:development?, nil).and_return(true)
      let(:mail) { Notifier.welcome_signup user }
      it "send an email to" do
        expect(mail.to).to eq([GlobalConstants::DEV_EMAIL_ADDRESS])
      end
    end
  end

【问题讨论】:

    标签: rspec rspec2 rspec-rails


    【解决方案1】:

    这里描述了一个更好的方法:https://stackoverflow.com/a/24052647/362378

    it "should do something specific for production" do 
      allow(Rails).to receive(:env) { "production".inquiry }
      #other assertions
    end
    

    这将提供像Rails.env.test? 这样的所有函数,并且如果你只比较像Rails.env == 'production' 这样的字符串也可以工作

    【讨论】:

    • 这是 RSpec 3 的方法。
    • 获取查询对象的更简洁的方法是"production".inquiry
    • @DavidBackeus:我不同意,我发现 Rails 用不相关行为污染对象的方式并不干净,但它绝对很方便。谢谢
    【解决方案2】:

    你应该存根itletbefore 块。把你的代码移到那里,它就可以工作了

    这段代码在我的测试中有效(也许你的变种也可以)

    Rails.env.stub(:development? => true)
    

    例如

    describe "in dev mode" do
      let(:mail) { Notifier.welcome_signup user }
    
      before { Rails.env.stub(:development? => true) }
    
      it "send an email to" do
        expect(mail.to).to eq([GlobalConstants::DEV_EMAIL_ADDRESS])
      end
    end
    

    【讨论】:

    • 并没有真正帮助。为“test”获取method_missing': undefined method stub':ActiveSupport::StringInquirer (NoMethodError)
    • 奇怪 - 我在发布代码之前检查了我的测试。提供您的代码和 gem 版本(rails、rspec)
    • 感谢它的工作。那么将它放在 it、let 或 before 块中的原因是什么?我认为“向它发送电子邮件”它块应该访问外部描述块中的任何内容。
    • 并非如此。这是一个相当复杂的问题。如果用两个词说:stubRspec 方法,Rspec 仅在提到的块内工作。其他原因是您应该在调用它之前存根方法,但是当您启动测试时 - Rspec 只读取需要的行:before allbefore eachit 块(let 块是延迟加载)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多