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
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:
spec.rb
file will be rolled back after the tests complete