How do I test a controller with rspec-rails?

喜欢而已 提交于 2019-12-11 01:59:27

问题


I want to test that my edit recipe page renders using rspec, though it doesn’t route to

    recipes/edit

it routes to recipes/id/edit (id being replaced with a number)

my current test looks like this

 describe "Show Edit Recipe Page" do

  it "should display edit recipe  page" do
    get :edit
    response.should be_success
    response.should render_template(:edit)
  end
end

how can i test this page correctly, at the moment my tests are failing


回答1:


Problem

Your example doesn't include the code needed to actually test a controller object. RecipeController is not defined in your spec.

Solution

Make sure your controller specs live under spec/controllers or have an explicit type: :controller set. Then, actually describe a controller, either using the implicit subject or by setting up a controller instance in a before or test block. As the most basic example:

describe RecipeController do
  # test something using the implied RecipeController.new
end

More Reading

RSpec Controller Specs




回答2:


The get needs the id of the recipe passed in the params hash:

let(:recipe) { Factory.create(:recipe) }

it "should display edit recipe page" do
  get :edit, :id => recipe.id
  response.should be_success
  response.should render_template(:edit)
end


来源:https://stackoverflow.com/questions/13185552/how-do-i-test-a-controller-with-rspec-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!