当从ERB切换到Angular时,Rails应用中的AngularJS视图会中断

Feature Testing AngularJS Views in a Rails App Breaks When Switching From ERB to Angular

本文关键字:应用 AngularJS 视图 中断 Rails ERB Angular 当从      更新时间:2023-09-26

首先,我有一个工作的rails 'show'页面,显示项目名称和属于项目的条目。当项目名称使用angular $scope显示,条目使用ERB中的块显示时,我的测试通过了。当我用angular指令'ng-repeat'替换条目的ERB代码时,只有条目的测试场景开始失败。有趣的是,该应用程序仍然可以在浏览器中运行。请记住,在我的视图中,另一个$scope变量使用几乎相同的测试仍然通过。

Working show.html.erb(在ERB中查看的条目):

<div ng-controller="ProjectCtrl">
  <h1>This is {{ project.details.name }}</h1>
  <h2>Entries</h2>
  <% @entries.each do |e| %>
  <ul>
    <li>
        <%= e.title %>
    </li>
    <li>
        <%= e.summary %>
    </li>
  </ul>
  <% end %>
</div>

break show.html.erb(在Angular中查看的条目):

<div ng-controller="ProjectCtrl">
  <h1>This is {{ project.details.name }}</h1>
  <h2>Entries</h2>
  <ul ng-repeat=" e in project.entries ">
    <li>
        {{ e.title }}
    </li>
    <li>
        {{ e.summary }}
    </li>
  </ul>
</div>

Angular控制器,数据已经被返回的JSON替换了。

@ProjectCtrl = ["$scope", "$http", ($scope, $http) ->
  $http.get().success (data) ->
    $scope.project = {"details":{"name":"Project1","author":"brian"},"updated_at":"2013-04-13T16:48:46.406Z","entries":[{"title":"Test Title","summary":"Summary Test"},{"title":"The Third Entry","summary":"Summary of Third Entry"}]}
]

这是一个示例测试,在用ng-repeat替换ERB之后失败了:

scenario "Displays Entries Summary" do
  project = Project.create!(details: {name: "aproject"})
  Entry.create!(data: {summary: "Should Be Displayed"}, project_id: project.id)
  Entry.create!(data: {summary: "Should Not Be Displayed"})
  visit project_path(project.id)
  page.must_have_content "Should Be Displayed"
  page.wont_have_content "Should Not Be Displayed"
end

我是否错过了什么,或者我是否必须改变我进行功能测试的方式?

为了使这个工作,我将Capybara的javascript驱动程序设置为poltergeist。这需要安装phantomJS(>= 1.8.1)并在集成测试中将js设置为true。

过程如下:

安装PhantomJS 1.9 (ubuntu 12.10与32位操作系统指示显示,相应调整):

$ cd
$ wget https://phantomjs.googlecode.com/files/phantomjs-1.9.0-linux-i686.tar.bz2
$ tar jxvf https://phantomjs.googlecode.com/files/phantomjs-1.9.0-linux-i686.tar.bz2
$ sudo mv phantomjs-1.9.0-linux-i686.tar.bz2
$ phantomjs --version

添加poltergeist到Gemfile和bundle install:

group :test do
  gem 'poltergeist'
end

在"test_helper. exe"文件中。

require 'capybara/poltergeist'
Capybara.javascript_driver = :poltergeist

在你的集成/特性测试中,一定要像这样包含'js: true':

scenario "Your test with Angular.js views", js: true do
  # test is here
end
# OR
it "Your test with Angular.js views", js: true do
  # test is here
end

在你的控制器中设置$scope。项目,所以在模板中的变量'项目'应该是可用的。在你粘贴的模板代码中,你是'重复'-重复'项目。条目(单数)除非你打错了或粘贴了伪代码,否则在浏览器中也无法工作。

我不太了解rails的功能测试,不能告诉你它会等到所有JS完成后再做断言。Angular中的路由改变怎么办?

我使用Angular的JS测试设置和karma和Jasmine来测试Angular页面。然后,Jasmine就会意识到Angular的堆栈处于活动状态。

查看这篇文章:http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-testacular.html