我已经安装 Devise 并将其集成到我的应用程序中,现在我正在构建它的测试套件。我正在使用 Rails 4.2.1 附带的默认测试套件 (Test::Unit?),目前正在开发集成套件。
集成测试:
def setup
@user = User.create(email: "user@hlist.com",
encrypted_password: Devise.bcrypt(User, 'password1'))
@post = { title: "This is the title",
content: "Detailed comment."*10,
phone: 9991118888,
email: "email@hlist.com",
user_id: users(:spiderman).id }
@p = @user.posts.build(@post)
end
test "creates a new post successfully" do
sign_in_as(@user)
get new_post_path(@user)
assert_template 'posts/new'
assert_difference 'Post.count', 1 do
post posts_path, post: @post
end
assert_template 'posts/show'
end
我还在我的 test_helper.rb 文件中创建了以下方法:
def sign_in_as(user)
post_via_redirect user_session_path, 'user[:email]' => user.email,
'user[:encrypted_password]' => Devise.bcrypt(User, 'password1')
end
但是,当我运行测试时出现以下错误:
1) Failure:
PostsCrudTest#test_creates_a_new_post_successfully [/Users/harishramachandran/dropbox/documents/harish/coding/workspace/h_list/test/integration/posts_crud_test.rb:19]:
expecting <"posts/new"> but rendering with <[]>
我在网上寻找解决方案,但我所能找到的都是涉及 RSpec 或 Capybara 的解决方案。这是我创建的一个应用程序,除其他外,在我继续使用不同应用程序中的 RSpec 和 Capybara 之前学习默认套件。有没有办法解决 Test::Unit 中的这个问题?
最佳答案
在 post posts_path, post: @post
中创建帖子后,您不会被重定向到帖子/节目。输入 follow_redirect!
就像这样:
发布 posts_path,发布:@post
关注重定向!
或者,您可以执行 post_via_redirect posts_path, post: @post
这将执行相同的操作。发布然后重定向到发布/显示。
一些注意事项 Devise.bcrypt 已于几天前弃用。所以将来如果你更新你的 Gemfile 你会得到一个弃用错误。 是的,您可以使用 Rails 默认测试进行集成测试。这是一个测试用户是否在登录或未登录的情况下获取根路径的示例。
require 'test_helper'
class UserFlowsTest < ActionDispatch::IntegrationTest
test "user can see home page after login" do
get user_session_path
assert_equal 200, status
@david = User.create(email: "david@mail.com", password: Devise::Encryptor.digest(User, "helloworld"))
post user_session_path, 'user[email]' => @david.email, 'user[password]' => @david.password
follow_redirect!
assert_equal 200, status
assert_equal "/", path
end
test "user can not see home page without login" do
get "/"
assert_equal 302, status
follow_redirect!
assert_equal "/users/sign_in", path
assert_equal 200, status
end
end
用于测试的 Rails 类(ActiveSupport::TestCase、ActionController::TestCase、ActionMailer::TestCase、ActionView::TestCase 和 ActionDispatch::IntegrationTest)继承自 minitest assertions 的断言不是test unit .这适用于您的 Rails 版本。
关于ruby-on-rails - 使用 Test::Unit 的集成测试设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491480/