stevec
stevec

Reputation: 52308

rspec test that uses dummy data from an entire table in rails app database

I want to write an rspec test that uses MyModel.all (i.e. all the records for a model) and does some things with it and returns a result

Is it possible to generate a new database table (i.e model) from within rspec? And then destroy it at the end of the test? Is this considered good practice (theoretically, if a dev working on the project coincidentally made a table of the same name and it could get dropped by the test). Or is this considered so unlikely it's okay to generate a randomly named table in a test?

Note: the test must extract all the records in the model, hence why it would be nice to simply generate one (a very small one) inside the test, rather than use an actual table, which may be large and slow down tests unnecessarily

The method I am trying to test is along the lines of

def my_method(model_name)
  the_table = eval(model_name).all

  # does some things

end

The key feature of the method is that it accepts the model name (and retrieves all the records for the model inside the method)

The test is along the lines of

it "ensures something" do

  # tests

  expect(result).to eq(true)

end

Upvotes: 1

Views: 2859

Answers (1)

stevec
stevec

Reputation: 52308

Here is an uncomplicated solution

Rails automatically creates a test db with the same schema as dev/prod. So all you need to do is add some data before you run your test

e.g.

# Add some records 
@model_name = Model_name.new(name: "John", email: "[email protected]")
@model_name.save

# run your test
it "ensures something" do

  # tests

  expect(result).to eq(true)

end

Also note:

  • Your rspec tests will use the test database, which is exactly the same structure as your development database, but just that it will start empty (hence why you have to add some data to it)
  • You can very easily put data in your test database in the same way that you would with your development (or production) databases
  • Note that anything you do to the test database in your spec.rb file will be rolled back after the tests complete

Upvotes: 1

Related Questions