Capybara + FactoryGirl,形式设定关系

Capybara + FactoryGirl, set relationship in form

我是 Capybara FactoryGirl 的新手,在我的 Rails 应用程序中,我的关系如下所示:

# App.rb
belong_to :plan

# Plan.rb
has_many :apps

每个应用程序都必须有一个计划,在我的 App.rb 模型中,我是这样做的:before_save :set_default_plan, on: :create

我想使用 Capybara 集成测试来测试应用创建是否有效。我目前有一个看起来像这样的测试:

require "rails_helper"

include Warden::Test::Helpers
Warden.test_mode!

describe "adding apps" do

  let(:user) { FactoryGirl.create(:user) }
  before { login_as(user, scope: :user) }

  it "allows a user to create an app" do
    visit apps_path
    fill_in "App name", with: "My App"
    click_on "create_app_button"
    visit apps_path
    expect(page).to have_content("My App")
  end
end

创建应用程序后,我在视图中呈现此内容:#{app.plan.free_requests}。如果我 运行 使用 bundle exec rspec 进行测试,我目前会收到此错误:

undefined method `free_requests' for nil:NilClass

在我的应用程序中,我还使用 FactoryGirl 来测试我的模型。我有以下(相关)工厂:

FactoryGirl.define do
  factory :app do
    name "Test"
    [...]
    association :plan, :factory => :plan
  end
end

FactoryGirl.define do
  factory :plan do
    name "Default"
    [...]
  end
end 

我想知道我应该如何设置我的工厂和测试套件才能使这个测试成为绿色测试。

我可以为我正在使用 Capybara 创建的应用程序分配一个计划,还是可以为我的应用程序使用 FactoryGirl 创建一个默认关联/计划。还有另一种方法吗?感谢所有帮助。

更新

这是我的 set_default_plan 方法的样子:

# App.rb
def set_default_plan
  if self.new_record?
    plan = Plan.find_by_stripe_id("default_plan")
    if plan.nil? == false
      self.plan = plan
    end
  end
end

FactoryGirl 在你的测试中真的不应该与 "apps" 或 "plans" 有任何关系,因为你 运行 通过你的控制器创建动作,除非 set_default_plan 如果 none 存在,则实际上不会创建计划。如果是这种情况,那么您可以使用 FactoryGirl 创建所需的计划,例如 - FactoryGirl.create(:plan) 在您的前块

您还应该指定该计划是必需的关联(这是 Rails 5 中的默认设置,因此如果您正在使用它,则可能没有必要)这将防止您的应用程序在没有计划。

# App.rb
belongs_to :plan, required: true

另一件需要注意的事情是,在访问另一个页面之前,您应该始终在单击执行某个操作的按钮后检查是否确认。这是因为不能保证单击按钮的结果是同步的,因此立即访问另一个页面可能会杀死操作请求。

click_on "create_app_button"
expect(page).to have_content("App Created!!!")  # whatever text is shown on success
visit apps_path