【问题标题】:Why is this FactoryGirl-created object visible in the test, but not in the view that is being tested?为什么这个 FactoryGirl 创建的对象在测试中可见,但在正在测试的视图中不可见?
【发布时间】:2014-01-02 18:11:28
【问题描述】:

我正在使用 RSpec、FactoryGirl 和 PhantomJS。


更新:

我已经验证,如果我在下面调用的 spec/support/login_macros.rb login_user 方法中创建此项目,则列表对象在视图中可用。

这似乎是 FactoryGirl 问题。为什么我可以使用该辅助方法从工厂创建,但不能在测试本身中创建?下面是支持方法:

module LoginMacros
  def login_user(admin = false)

    myrepo = FactoryGirl.create(:repository, :myname)
    plan = FactoryGirl.create(:plan, name: "Test Multi", listing_limit: 5000, repositories_allowed: 5)

    user = FactoryGirl.create(:user)

    subscription = FactoryGirl.create(:subscription, user: user, plan: plan)
    user.add_repository(myrepo)
    listing = FactoryGirl.create(:listing, user: user, repository: myrepo)

    visit login_path
    fill_in 'Email', :with => user.email
    fill_in 'Password', :with => user.password
    click_button 'Go'
    user
  end

我在spec_helper.rb 中将transactional_fixtures 设置为false。这是我的规格:

require "spec_helper"

describe "App Integration" do

  let!(:user) { login_user }
  let!(:myrepo) { user.repositories.where(name: "myrepo" ).first }

  it "lets a user add apps to a listing", js: true do
    listing = FactoryGirl.create(:listing, user: user, repository: myrepo)
    puts listing.inspect
    Capybara::Screenshot.screenshot_and_open_image
  end

end

现在问题来了。看到上面的puts 行了吗?它打印出对象。

但在屏幕截图中,就好像对象从未创建过。就像魔术一样!

然而,User 和 Repository 对象在视图中都是可见的。

另外,我可以转到不同的视图并查看 Listing 对象。只是不在我的应用程序的主页上!

为什么该对象在一个视图中可见,而在另一个视图中不可见?我只是在主页上这样做:

<h3><%= Listing.count %></h3>

而且它总是,总是,总是零。零意义。

【问题讨论】:

    标签: ruby-on-rails-3 rspec factory-bot


    【解决方案1】:

    您似乎从未在测试中调用过visit,因此该页面将始终为空白。保存截图前需要拨打visit root_path # (or whatever path that heading is on)。

    【讨论】:

    • visit 在 login_user 方法中被调用。确实出现了正确的屏幕,但它只是没有看到已创建列表对象。它看到 User 和 Repository 对象在数据库中,但仅此而已。
    • 即使是同一个页面,我也需要“重新访问”该页面,因为它正在呈现在创建对象之前访问过的内容。
    【解决方案2】:

    let! 块在 it 块之前被调用。由于您在 let! 块中查看页面,但在 it 块中创建 listing,因此在您查看页面之前不会创建列表。

    【讨论】:

    • 我如何查看let! 块中的页面?截图行位于it 块中。
    • 屏幕截图将当前正在查看的内容保存到文件中;它实际上并没有访问该页面。 visit 和 click_button 调用是与页面实际交互的。
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2014-11-23
    • 2017-04-27
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多