【发布时间】:2016-07-19 17:37:54
【问题描述】:
我是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
【问题讨论】:
标签: ruby-on-rails ruby rspec capybara factory-bot