简体   繁体   English

如何使用RSpec测试脚本?

[英]How do I test a script using RSpec?

I'm writing a script that will be run using rails runner on production to make some one-time changes to our database. 我正在编写一个脚本,该脚本将在生产中使用rails runner运行,以对我们的数据库进行一些一次性更改。 I want to be sure that the script works as expected before we run it, so I'm writing RSpec tests to verify its behavior while I write it. 我想确保脚本在运行之前能够按预期运行,因此我正在编写RSpec测试以验证其编写时的行为。

How can I invoke the script in my test examples? 如何在测试示例中调用脚本? The script isn't a class or a module, so there aren't individual functions for me to test. 该脚本不是类或模块,因此没有供我测试的单独功能。 Instead, the entire script will be loaded once, run from top to bottom, and then exited. 相反,整个脚本将被加载一次,从上到下运行,然后退出。 I'm not sure how to invoke that from within an RSpec test. 我不确定如何从RSpec测试中调用它。

I'm looking for something like: 我正在寻找类似的东西:

describe "my script" do
  it "should create the correct record" do
    before_count = Orders.count

    rails runner my_script.rb # What goes here?

    expect(Orders.count).to eq(before_count + 1)
  end
end

I would move the logic from the script into its own class. 我会将逻辑从脚本移到其自己的类中。 Then you can invoke the class in your script and in your tests or even when you're in the rails console. 然后,您可以在脚本和测试中甚至在Rails控制台中调用类。 I've been using this pattern for a while and its pretty useful. 我使用这种模式已有一段时间了,它非常有用。

I think you want to use system : 我认为您想使用system

system('rails runner my_script.rb')

edit #1 编辑#1

If you are willing to butcher the script, you can move the active components of your script into separate module and require that: 如果您愿意保留脚本,则可以将脚本的活动组件移动到单独的模块中,并require

# my_script.rb
require './lib/my_script.rb'
MyScript.call()
# lib/my_script.rb
module MyScript
  def self.call
    # your code
  end
end

Then, in test: 然后,在测试中:

require './lib/my_script.rb'

describe "my script" do
  it "should create the correct record" do
    before_count = Orders.count

    MyScript.call() # here

    expect(Orders.count).to eq(before_count + 1)
  end
end

It looks like I can use Kernel#load to execute the script: 看来我可以使用Kernel#load执行脚本:

describe "my script" do
  it "should create the correct record" do
    before_count = Orders.count

    load(Rails.root.join("path", "to", "my-script.rb")

    expect(Orders.count).to eq(before_count + 1)
  end
end

We can help you with this, but this: 我们可以为您提供帮助,但这是:

I'm writing a script that will be run using rails runner on production to make some one-time changes to our database. 我正在编写一个脚本,该脚本将在生产中使用RailsRunner运行,以对我们的数据库进行一些一次性更改。

Is what migrations are for. 这就是迁移的目的。 One time changes like this to the db should be done in a migration. 一次对数据库进行这样的更改应该在迁移中完成。 This circumvents the need for rspec, as any changes like this should be reversible , as migrations should be. 这避免了对rspec的需求,因为像迁移这样的任何更改都应该是可逆的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM