[rspec-users] What should I test/specify?

Andrew Wagner wagner.andrew at gmail.com
Sat Oct 30 13:12:52 EDT 2010


Yeah, that's about what I figured, thanks. This is what I came up with:

require 'spec_helper.rb'
require 'yaml'

describe "BTree" do
  describe ".load_file" do
    context "when the file exists" do
      before(:all) { File.open("test_file.yaml", 'w') {|f| } }
      after(:all) { File.delete "test_file.yaml"}

      after(:each) { BTree.load_file "test_file.yaml" }
      it "parses the yaml in the file" do
        YAML.stub!(:load_file).and_return(:foo)

 YAML.should_receive(:load_file).with("test_file.yaml").and_return(:foo)
      end

      it "converts the raw data into a tree" do
        fake_creator = Object.new

        fake_creator.stub! :create
        YAML.stub!(:load_file).and_return(:data)
        BehaviorCreator.stub!(:new).and_return :tree

        BehaviorCreator.should_receive(:new).with(:data).and_return
fake_creator
        fake_creator.should_receive :create
      end
    end

    context "when the file doesn't exist" do
      it "raises an error" do
        lambda { BTree.load_file "non_existent.yaml" }.should raise_error
      end
    end
  end
end


On Sat, Oct 30, 2010 at 12:47 PM, John Feminella <johnf at distb.net> wrote:

> If you're writing a unit test for a method, the general rule of thumb
> is to test what the method itself does. That sounds tautological, but
> it's meant to define the boundary of what you should and shouldn't
> care about.
>
> In this case, you only care about the fact that `YAML::load_file` is
> called, and that `BehaviorTreeCreator.new` is then called with the
> result of that, and that *that* result has `create` invoked on it.
> That's it: if those three things happen, then this method is working
> as you expect.
>
> Your unit tests for BehaviorTreeCreator.new and .create will probably be
> richer.
>
> ~ jf
> --
> John Feminella
> Principal Consultant, BitsBuilder
> LI: http://www.linkedin.com/in/fjsquared
> SO: http://stackoverflow.com/users/75170/
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20101030/0c91b8c3/attachment.html>


More information about the rspec-users mailing list