File creation

I have a model that generates the authorization_rules.rb for
declarative_auth. I am not sure how I can go about testing the model -
apart from anything I don’t want my test to over-write the file - so,
er, I am not quite sure how to go about it.

I could have some sort of sniffer in my model to see if I am in the
Test environment and generate a different file, but putting code into
my model to pass tests doesn’t seem a very, well, sensible thing to
do.

Anyone been there, done that?

Ben

On Thu, Apr 22, 2010 at 9:28 AM, ben rooney
[email protected] wrote:

Anyone been there, done that?
Assuming that in you code you write the file with say

File.open(path_to_authorization_rules_dot_rb, ‘w’) do | f |
#code to write the file contents to f
end

where path_to_authorization_rules_dot_rb is some constant, variable or
expression which evaluates to the path to the file.

You could do something like

@iostream = StringIO.new
File.stub(:open) { yield @iostream}

call your code

test the contents of @iostream.string

This should work assuming your code doesn’t open any other files.

Another way would be to extract the code in the open block to a
separate method which takes the IO object as a parameter, and test
that method passing in a StringIO.


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale