ruby-on-rails - 如何期待 'render template' 错误

标签 ruby-on-rails ruby rspec

我有一个 View 模板“show.html.haml”,类似

- if current_user.admin?
  balabala

它将得到“undefined method `admin?'”对于 nil:NilClass"而 GET #show。我用“- if !current_user.nil? && current_user.admin?”修复了它。我想用 RSpec 添加一个测试用例。

describe "before login user - " do

  it "render the show template" do
    book = FactoryGirl.create(:book)
    get :show, id: book.id

    expect(response).to render_template("show")
    expect(response).to be_success
  end
end

在运行“bin/rake spec”时,无论我是否添加条件“!current_user.nil?”,它总是会成功。当我想检查渲染“显示” View 是否成功时,如何编写 expect 子句?

最佳答案

当您尝试测试来自 controller spec 的 View 内容时,你不能直接这样做。

您可以使用 render_views声明这样做,但不推荐,您应该选择 request specfeature spec测试完整的请求-响应周期。

全局设置render_views:

RSpec.configure do |config|
  config.render_views
end

规范:

describe "before login user - " do
  it "render the show template" do
    book = FactoryGirl.create(:book)
    get :show, id: book.id
    expect(response).to render_template("show")
    expect(response.body).to match /balabala/
  end
end

关于ruby-on-rails - 如何期待 'render template' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189748/

相关文章:

ruby - Carrierwave Gem 和 rmagick

ruby - 给定一个类和一个 UnboundMethod 定义一个实例方法

ruby-on-rails - 用户密码更新rspec

ruby-on-rails - Mechanize 帖子让我无法验证 CSRF token 的真实性

ruby-on-rails - collection_select onchange 事件和选定的 ruby​​ on Rails

ruby-on-rails - 如何外部化 Rails 模型 (api/gem/plugin)

ruby-on-rails - Rails - 在没有 layouts/application.html.erb 内容的情况下显示链接 View

ruby-on-rails - 设计和 Rspec - 未定义的方法 `authenticate!' 为 nil :NilClass

ruby-on-rails - Ruby on Rails 是否鼓励人们违反 YAGNI?

ruby-on-rails - 使用 STI 的带有回形针的多个模型