mock Rails.env.development?使用rspec
我正在使用rspec编写一个单元测试 我想模拟Rails.env.developement?返回真值。我怎样才能做到这一点 我试过这个mock Rails.env.development?使用rspec,rspec,rspec2,rspec-rails,Rspec,Rspec2,Rspec Rails,我正在使用rspec编写一个单元测试 我想模拟Rails.env.developement?返回真值。我怎样才能做到这一点 我试过这个 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 "t
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,
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
你应该在块之前插入
it
,let
,。将代码移到那里,它就会工作
这段代码可以在我的测试中使用(也许你的变体也可以使用)
比如说
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.test?
,如果您只是比较字符串,如Rails.env=='production'
没有真正的帮助,它也可以工作。获取method_missing':未定义的“test”方法stub':ActiveSupport::StringInquirer(NoMethodError)奇怪-我在发布代码之前检查了我的测试。提供gems(rails,rspec)的代码和版本,感谢它的工作。那么,在it、let或before块中使用它的原因是什么?我认为“发送电子邮件到”it块应该访问外部描述块中的任何内容。找到了。事实并非如此。这是一个相当复杂的问题。如果用两个字说:stub
是一个Rspec
方法,Rspec只在所提到的块内工作。另一个原因是您应该在调用存根方法之前,但在启动测试时-Rspec只读取所需的行:在所有之前
,在每个之前
,它
块(让
块是延迟加载),这是Rspec 3的方法。获取查询对象的更干净的方法是执行生产操作.inquiry
@DavidBackeus:我不同意,我发现Rails用不相关的行为污染物体的方式并不干净,但它确实很方便。谢谢
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
it "should do something specific for production" do
allow(Rails).to receive(:env) { "production".inquiry }
#other assertions
end