Rails测试设计控制器的简单示例

时间:2015-05-28 09:27:05

标签: ruby-on-rails devise tdd

我想要最简单的示例来测试设计属性对新注册(电子邮件,密码,密码确认),sign_in和forgot_password的有效性。互联网上到处都是RSpec,但是我想用Rails 4.2给我的东西,并没有什么。

我坚持使用默认实现:

require 'test_helper'

class RegistrationsControllerTest < ActionController::TestCase

  def setup
    @controller = RegistrationsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    @request.env["devise.mapping"] = Devise.mappings[:user]
    @user = Registrations.new(username: "John", email: "myemail@email.com")
  end

end

我知道这不是太多但是我在TDD上迈出了第一步,所以请不要拍!

如何检查用户属性的有效性,例如无邮件或100个字符的密码?

1 个答案:

答案 0 :(得分:0)

您可以使用rails in-build minitest

进行检查

我认为你已经覆盖了设计的registration_controller。

在控制器的tdd中,您可以编写测试用例以进行操作。 检查修改后的代码: -

require 'test_helper'

class RegistrationsControllerTest < ActionController::TestCase
  include Devise::TestHelpers # for including devise's actions

  def setup # this set up default settings for controller
    @controller = RegistrationsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    @request.env["devise.mapping"] = Devise.mappings[:user]
    @user = Registrations.new(username: "John", email: "myemail@email.com")
  end

  setup do # this used for setting global variable used in test file 
    @user= users(:one) # users is the fixture file of test in which you can set default data for test environment.
  end

  test "should create user" do # then you test cases for controller
    sign_in users(:one)
    post :create, users:{email:'test@test.com, password:'XXXX'...}# you can pass arguments for create method. Please check it once, i am not sure about names
    assert_response :success 
  end


end

Rails minitest提供了一些assertion