Rails 3 RSpec和assert_select

时间:2012-02-07 15:35:33

标签: ruby-on-rails-3 rspec

我曾想过尝试使用Rspec。但我得到了assert_select的下一个问题。

1) UserController login page open login page contains all expected controls
Failure/Error: assert_select "form[action=?]", "/user/login" do MiniTest::Assertion:
Expected at least 1 element matching "form[action='/user/login']", found 0.
# (eval):2:in `assert'
# ./spec/controllers/user_controller_spec.rb:20:in `block (3 levels) in <top (required)>'

这是我的代码段

describe UserController do
  describe "login page open" do
    it "login page contains all expected controls" do
      get :login
      assert_select "form[action=?]", "/user/login" do
      assert_select "input[name=?]", "username"
      assert_select "input[name=?]", "password"
      assert_select "input[type=?]", "submit"
    end
  end
end

当我在浏览器中打开登录页面时,此页面打开没有问题。

2 个答案:

答案 0 :(得分:17)

默认情况下,RSpec(至少在较新版本中)会阻止Rails在运行控制器规格规范时呈现视图。他们希望您在视图规格中测试您的视图,而不是控制器规格。由于视图不呈现,assert_select总是失败。

但是对于那些(像我一样)想要在控制器规范中测试视图的偶然片段的人来说,他们提供了render_views方法。您必须在describecontext块中调用它,而不是在it块内。

describe UserController do

  render_views       # <== ADD THIS

  describe "login page open" do
    it "login page contains all expected controls" do
      get :login
      assert_select "form[action=?]", "/user/login" do
      assert_select "input[name=?]", "username"
      assert_select "input[name=?]", "password"
      assert_select "input[type=?]", "submit"
    end
  end
end

答案 1 :(得分:1)

控制器测试用于测试控制器。

assert_select匹配视图代码中的内容。

将控制器与视图分开是一个好主意,这包括在控制器和视图上完成的测试。您应该在视图测试中使用assert_select(通常在spec/views上),而不是在控制器测试中。