开发者

Rails 3.1, RSpec - failing but page loads fine

开发者 https://www.devze.com 2023-04-10 23:58 出处:网络
I am writing some specs and the following is failing but the page /menus/1 is loading fine in a browser. This is a port of a php app and is first time I\'ve used RSpec. Any thoughts as to why it might

I am writing some specs and the following is failing but the page /menus/1 is loading fine in a browser. This is a port of a php app and is first time I've used RSpec. Any thoughts as to why it might not be working.

The error is:

1) MenusController GET 'show' should be succesful
  Failure/Error: get :show, :id => 1
  ActiveRecord::RecordNotFound:
  Couldn't find MenuHeader with id=1
  # ./app/controllers/menus_controller.rb:18:in `show'
  # ./spec/controllers/menus_controller_spec.rb:7:in `block (3 levels) in <top (required)>'

but that specific MenuHeader does exist based upon all normal criteria (console, mysql, browser). I'm 99% sure I have a mistake in my spec:

require 'spec_helper'

describe MenusController do开发者_高级运维
  describe "GET 'show'" do
     it "should be succesful" do
       get :show, :id => 1
       response.should be_success
     end
  end
end

here is the menus_controller.rb

def show
  @menu_header_data=MenuHeader.find(params[:id])


  respond_to do |format|
    format.html # show.html.erb
    # format.json { render json: @menu } to do
  end
end

thx


When testing a controller with Rspec or TestUnit I would use a Factory or Fixture to pass the id rather than setting up a test database with data. It's better to test with something like:

Using FactoryGirl (My Recommendation but everyone has their own tastes):

describe MenusController do
  describe "GET 'show'" do
     it "should be succesful" do
       get :show, :id => Factory(:menu).id
       response.should be_success
     end
  end
end

The test is mainly just to make sure the controller responds properly when provided valid data, and using Factories or Fixtures is much less brittle. It will become a pain to maintain your test suite if it's based on hard data like fixtures or a db backup, and that could ultimately lead to you giving up on Test Driven Development rather than embracing it.

0

精彩评论

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