Search code examples
ruby-on-rails-3rspecfactory-botfactories

Best way to modify factory attributes for multiple tests?


Trying to test some routing with rspec and factories. What would be the best way to modify an existing factory multiple times inside the spec test?

require "spec_helper"

describe gameController do
  describe "routing" do

    game = FactoryGirl.create(:game)

    it "routes to #show" do
      get("/game/1").should route_to("game#show", :id => "1")
    end

    it "routes to #show" do
      # need to modify 1 param of the factory.. how best to do this?
      get("/game/1").should route_to("game#show", :id => "1")
    end

  end
end

Solution

  • You basically have two options. If you're just modifying a single param between test, it might be easiest just to do something like:

    before(:each) do
      game = FactoryGirl.create(:game)
    end
    
    it "does something" do
      get("/game/1").should route_to("game#show", :id => "1")
    end
    
    it "does something else" do
      game.update_attributes(:param => "value")
      get("/game/1").should route_to("game#show", :id => "1")
    end
    

    Otherwise, you could set up a factory girl sequence and do a fresh FactoryGirl.create in each spec.