失败/错误:response.should render_template(:new)expecting<“new”>但使用<“”>进行渲染

时间:2016-11-10 06:27:05

标签: ruby-on-rails ruby rspec

posts_controller.rb

class PostsController < ApplicationController
  respond_to :html, :xml, :json  
  before_filter :authenticate_user!, :except => [:show, :index]
  before_filter :admin_only, :except => [:show, :index]

  def new
   @post = Post.new
  end
end

spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'forgery'
require 'populators'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/test/fixtures"

  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
  end

  config.after(:suite) do
    DatabaseCleaner.clean
  end

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = false
end

posts_controller_spec.rb

require File.dirname(__FILE__) + '/../spec_helper'

describe PostsController do
  fixtures :all
  include Devise::TestHelpers
  render_views

  before(:each) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.start
  end

  after(:each) do
    DatabaseCleaner.clean
  end
  it "new action should render new template" do
    get :new
    response.should render_template(:new)
  end
end
  

ruby​​ 1.8.7,rspec 2.11,Rails 3.2.19

我收到此错误期待&lt;“new”&gt;但用&lt;“”&gt; 进行渲染我怎么能通过这个案子...我尝试了很多建议但没有取得任何成功..请帮助我坚持下去...... :(

注意:我无法更改控制器的代码

1 个答案:

答案 0 :(得分:0)

# Use the sign_in helper to sign in a fixture `User` record.
user = users(:one)

@request.env['warden'].stub(:authenticate!).and_return(user)
@controller.stub(:current_user).and_return(user)

get :new
assert_template 'new'

这适用于我使用https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs和thanx @Зелёный的方向:)