Skip to content

Instantly share code, notes, and snippets.

@jwo
Created October 29, 2012 16:41
Show Gist options
  • Save jwo/3974731 to your computer and use it in GitHub Desktop.
Save jwo/3974731 to your computer and use it in GitHub Desktop.
No Instance Variables in Specs (for @Blighte)

(this started on twitter)

The microposts spec starts out with

let(:user) { FactoryGirl.create(:user) }
  before do
    # This code is wrong!
    @micropost = Micropost.new(content: "Lorem ipsum", user_id: user.id)
  end

  subject { @micropost }

Michael is telling you the code is wrong to set an instance variable in the spec. Instead, you should just:

  let(:user) { FactoryGirl.create(:user) }
  subject { Micropost.new(content: "Lorem ipsum", user_id: user.id) }

This way, the subject is set to the Micropost.new

The same happens in my Dog example... We are setting the subject to a new instance of Dog.

describe Dog do

This will set the subject to Dog.new

class Dog
def initialize(name="sparky")
@name = name
end
def name
@name
end
end
require 'rspec'
require './dog'
describe Dog do
it { should respond_to(:name) }
end
@mhartl
Copy link

mhartl commented Oct 30, 2012

That's not why the code is wrong. Using instance variables in specs is fine, although I prefer to use let when I can. The code is wrong because setting the user_id doesn't work as soon as you define attr_accessible. Instead, you need to define the micropost through the association, using code like user.microposts.build(...), as described in Section 10.1.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment