Search code examples
ruby-on-railsrspecfactory-botrspec-rails

Using Factory Girl with Rspec Views


So I want to test some views using Rspec and Factory Girl, but I don't know how to assign a factory to a view properly. All of the information I see online uses stubbing, and although stubbing is fine, I want to keep my rspec stuff somewhat consistent.

I want to use a factory for an edition model and associate that with the page when I render the page, but everything I've considered seems to be broken. Here's sort of a ridiculous example:

require 'spec_helper'

describe "catalog/editions/rationale.html.haml" do
  before do
    @edition = Factory.create(:edition)
    assign(:editions, @edition)
    render :action => 'rationale', :id => @edition
  end
  context "GET rationale" do
    it "should not have the preamble to the United States constitution" do
      rendered.should_not contain(/We the People of the United States/)
    end
  end
end

In this I've tried changing render :action => 'rationale', :id => @edition to just render, and other similar tweaks to the render action. I just have no idea where to start a factory_girl helped view. Any help would be greatly appreciated.

Versions:

Rails 3.0.10

RSpec 2.7

Factory_Girl 2.2


Solution

  • I think the error is that @editions is expecting an array, so you should write

    assign(:editions, [@edition])
    

    or, otherwise, if it should be a single element, you should write:

    assign(:edition, @edition)
    

    Secondly, unless your view is a partial that expects variables, you should just write

    render
    

    You do not have to give the action, rspec knows which view to render from the describe, and the view does not retrieve any data (so you don't have to set the id), you just have to set the instance variables correctly using the assigns. Testing the view does nothing more than rendering the view.

    Hope this helps.