测试从Typus继承的Rails控制器

时间:2011-05-18 21:17:47

标签: ruby-on-rails functional-testing

我已经和它斗争了几天,网上似乎没什么帮助。我查看了Typus wiki,示例应用程序和测试,我似乎正在做正确的事情,但我仍然得到HTTP状态代码302(重定向),在我的测试中我期望200(成功)。

以下是适当的文件(删除了无关的内容)

config / initializers / typus.rb(rails g typus:已经运行了迁移,因为我有一个admin_users表):

Typus.setup do |config|

  # Application name.
  config.admin_title = "Something"
  # config.admin_sub_title = ""

  # When mailer_sender is set, password recover is enabled. This email
  # address will be used in Admin::Mailer.
  config.mailer_sender = "noreply@somewhere.com"

  # Define paperclip attachment styles.
  # config.file_preview = :medium
  # config.file_thumbnail = :thumb

  # Authentication: +:none+, +:http_basic+
  # Run `rails g typus:migration` if you need an advanced authentication system.
  config.authentication = :session

  # Define user_class_name.
  config.user_class_name = "AdminUser"

  # Define user_fk.
  config.user_fk = "admin_user_id"

  # Define master_role.
  config.master_role = "admin"
end

配置/ typus / admin_user.yml

AdminUser:
  fields:
    default: first_name, last_name, role, email, locale
    list: email, role, status
    form: first_name, last_name, role, email, password, password_confirmation, locale
    options:
      selectors: role, locale
      booleans:
        status: Active, Inactive
  filters: status, role
  search: first_name, last_name, email
  application: Admin
  description: Users Administration

测试/工厂/ admin_users.rb:

Factory.define :admin_user do |u|
  u.first_name 'Admin'
  u.last_name 'User'
  u.email 'admin@somewhere.com'
  u.role 'admin'
  u.password 'password!'
  u.token '1A2B3C4D5E6F'
  u.status true
  u.locale 'en'
end

测试/功能/管理/ credits_controller_test.rb:

require 'test_helper'

class Admin::CreditsControllerTest < ActionController::TestCase
  setup do
    @admin_user = Factory(:admin_user)
    @request.session[:admin_user_id] = @admin_user.id
    @request.env['HTTP_REFERER'] = '/admin/credits/new'
  end

  context "new" do
    should "be successful" do
      get :new
      assert_response :success
    end
  end
end

@ response.body:

<html>
  <body>You are being <a href="http://test.host/admin/session/new?back_to=%2Fadmin%2Fcredits%2Fnew">redirected</a>.
  </body>
</html>

正如您所看到的,我已经设置了使用admin_user和admin_user_id作为会话密钥的类型。但由于某些原因,测试失败了302而不是200.我确信这是因为我做错了,我只是看不到。我还创建了所有这些gist,以防万一有人更喜欢。

编辑2011-05-19 09:58 am Central Time:为每个请求添加了响应正文。

1 个答案:

答案 0 :(得分:0)

我想出来了。这是config / typus / admin_roles.yml文件的问题。

之前:

admin:
  Category: create, read, update
  Credit: read
  ...

之后:

admin:
  Category: create, read, update
  Credit: read, create
  ...

问题是管理员用户无法访问admin / credits_controller上的CREATE操作,导致用户被发送回管理员登录地址。

授予管理员用户访问权限并更改

的权限
@session[:admin_user_id]

@session[:typus_user_id] #Just like in the Typus docs

解决了这个问题。由于

,我已将其更改为:admin_user_id
config.user_fk = "admin_user_id"

在typus配置文件中,同时尝试解决此问题。