mock Rails.env.development? using rspec

久未见 提交于 2019-12-03 07:38:16

问题


I am writing a unit test using rspec.

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

I tried this

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

it throws this error

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

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

回答1:


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)

for example

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



回答2:


There is a much better way described here: https://stackoverflow.com/a/24052647/362378

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

This will provide all the functions like Rails.env.test? and also works if you just compare the strings like Rails.env == 'production'



来源:https://stackoverflow.com/questions/21153666/mock-rails-env-development-using-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!