开发者

RSpec controller test fails - how to load mock data?

开发者 https://www.devze.com 2023-02-17 00:20 出处:网络
I have 2 simple RSpec tests i\'ve written for a small rails app i\'ve done to learn rails. I originally had a mock setup for my Link class but was getting the same issue.

I have 2 simple RSpec tests i've written for a small rails app i've done to learn rails. I originally had a mock setup for my Link class but was getting the same issue.

This is my test code:

require 'spec_helper'

describe LinksController do
  render_views
  before(:each) do
    link = Link.new
    link.stub!(:title).and_return("Reddit")
    link.stub!(:url).and_return("http://www.reddit.com")
    link.stub!(:created_at).and_return(Time.now)
    link.stub!(:updated_a开发者_如何学编程t).and_return(Time.now)
    link.stub!(:user_id).and_return("1")
    link.stub!(:id).and_return("1")
    link.save

    user = User.new
    user.save
  end

  it "renders the index view" do
    get :index
    response.should render_template('links/index')
    response.should render_template('shared/_nav')
    response.should render_template('layouts/application')
  end

  it "renders the show view" do
    get :show, :id => 1
    response.should render_template('links/show')
    response.should render_template('shared/_nav')
    response.should render_template('layouts/application')
  end
end

I'm new to both rails and RSpec, not sure what I should be doing to get this to work. What is the best way to test this show method from my LinksController when you need data? I tried mock_model too but maybe I was using it wrong.

You can see all the app code on Github


The problem is that you are stubbing a model, so it's not stored in the database. That means that when you call get :show, :id => 1 the query to the database returns nothing and your tests fail. Stubbing is great when you want to fake a response or an object without using the database, but if you are depending on actual Rails code that uses the database you can't use this method because nothing exists in the database. To fix this I would drop the stubbed models entirely and actually create them.

require 'spec_helper'

describe LinksController do
  render_views
  before(:each) do
    user = User.create

    @link = Link.create :title => "Reddit",
                        :url => "http://www.reddit.com",
                        :user => user
  end

  it "renders the index view" do
    get :index
    response.should render_template('links/index')
    response.should render_template('shared/_nav')
    response.should render_template('layouts/application')
  end

  it "renders the show view" do
    get :show, :id => @link.id
    response.should render_template('links/show')
    response.should render_template('shared/_nav')
    response.should render_template('layouts/application')
  end
end

You should also eventually look into Factory gems like Sham and Factory Girl to simplify the creation of test data.

0

精彩评论

暂无评论...
验证码 换一张
取 消