On Nov 14, 2007 11:02 AM, David W. [email protected] wrote:
I’m just getting started with rspec. Two questions:
- Should the rspec be in the same file as the production code? The
examples on the rspec site seem to indicate they should be in a separate
file but I wanted to double check.
Specs should be separate. In a Rails app there’s a spec dir that
parallels your app dir. If you’re writing a Ruby app from scratch
then you’ll need to create it yourself. But definitely stick specs in
separate files from production code.
and I want to do a mock database connection do I have to write the
production code like:
def read(db=database.instance())
db.execute(…)
end
and then call it with read(my_mock) ?
You can do it that way, or you can stub the call to #instance and have
it return the mock.
Also, without knowing anything about your code I would be more
likely to pass the datastore into the constructor:
class Person
def initialize(datastore)
@datastore = datastore
end
def read
conn = @datastore.instance
conn.execute(…)
end
end
Then your spec would look something like:
describe Person, " reading a record" do
before(:each) do
@mock_connection = mock(“db connection”)
@mock_pool = stub(“connection pool”, :instance => @mock_connection)
@person = Person.new @mock_pool
end
it “should get a connection” do
@mock_pool.should_receive(:instance).and_return @mock_connection
@person.read
end
it “should select data from the database” do
@mock_connection.should_receive(:execute).with(…)
@person.read
end
end
Which is sort of ugly because you have a mock returning a mock, but
such is life with a singleton
Pat