模拟 Rails.env.development?使用 rspec [英] mock Rails.env.development? using rspec

查看:21
本文介绍了模拟 Rails.env.development?使用 rspec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a unit test using rspec.

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

I would like to mock Rails.env.develepment? to return true. How could I achieve this?.

我试过了

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 版本 ruby​​-2.0.0-p353,导轨 4.0.0,规范 2.11

Update ruby version ruby-2.0.0-p353, rails 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

推荐答案

你应该在 itletbefore 块中存根.将您的代码移到那里,它会起作用

You should stub in it, let, before blocks. Move your code there and it will work

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

And this code works in my tests (maybe your variant can work as well)

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

这篇关于模拟 Rails.env.development?使用 rspec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆