**EDIT**:

I managed to solve my original problem.

As described below, I had problems running the rails runner from within rspec. A detail I now realise is probably relevant is that my rspec tests are in an entirely different project, which doesn't include Rails.

The problem turned out to be that the environment variable `BUNDLE_GEMFILE` was set to point to the `rspec` project, i.e. a set of gems which didn't include Rails. Setting it like so:

```
ENV['BUNDLE_GEMFILE'] = nil

```

before calling my `system` command caused everything to spring into life.

**Original Question:**

The following command works from my terminal:

```
ruby <path to rails app>/script/rails runner <cmd>

```

However trying to run the same command from within a ruby script (rspec) doesn't, it fails with:

```
<path>/script/rails:6:in `require': cannot load such file -- rails/commands (LoadError)

```

This is the command:

```
system("ruby <path to rails app>/script/rails runner <cmd>")

```

I assume this is a problem with different environments between the terminal (bash) and the system command in ruby. Is there a way to make the ruby script use the same environment?

**EDIT**:

I tried to set the environment as per @Eternal-Learner's answer below, but that didn't make any difference to the error. Possibly that indicates that the problem is not the environment, but if it isn't what could it be?

**EDIT 2:**

It looks like this is a problem with rspec. I tried running the command in a normal ruby script, not in an rspec example, and bingo!...everything works.

So why should it matter that I'm running in rspec? I expected that running a `system` command would start a new instance of the Ruby interpreter, and hence outside of the rspec environment. Is there some sort of Ruby global between different instances of the Ruby interpreter, or does system not create a new Ruby environment?