Ale*_*alm 5 ruby testing rspec selenium-webdriver factory-bot
我正在使用带有 selenium-webdriver gem 的 Rspec 来测试 Web 应用程序。我想在我的测试中不包括工厂来模拟用户,而不是每次都手动创建一个用户。因此,我制作了 gem install factory_girl,在我的 spec_helper 中添加了 required 行,创建了一个工厂并在我的 spec 文件中包含了一些行。并且在运行测试时我得到一个错误 Failure/Error: FactoryGirl.build(:user) NameError: uninitialized constant User
这是我的 spec_helper.rb
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
Run Code Online (Sandbox Code Playgroud)
我的 factory.rb 文件:
FactoryGirl.define do
factory :user do
name "testuser"
password "freestyle"
inventory true
end
end
Run Code Online (Sandbox Code Playgroud)
我的 test_spec 文件:
require "json"
require "selenium-webdriver"
require "rspec"
require "factory_girl"
FactoryGirl.find_definitions
include RSpec::Expectations
describe "MallSpec" do
before(:all) do
FactoryGirl.build(:user)
@driver = Selenium::WebDriver.for :firefox
@base_url = "http://localhost:9000/"
@accept_next_alert = true
@driver.manage.timeouts.implicit_wait = 30
@driver.manage.window.resize_to(1301, 744)
@verification_errors = []
end
Run Code Online (Sandbox Code Playgroud)
我的 spec_file 位于项目的根目录中。我的 factory.rb 文件位于 /spec 目录以及 test_spec.rb 本身。谁能帮我解决这个问题或指出我做错了什么?
运行测试时出现错误 Failure/Error: FactoryGirl.build(:user) NameError: uninitializedconstant User
必须定义您的用户类别。以下是定义的测试no User class:
require 'factory_girl'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
FactoryGirl.define do
factory :user do
name 'Alice'
age 10
end
end
describe "MallSpec" do
let(:test_user) { FactoryGirl.build(:user) }
describe "user's name" do
it "equals 'Alice'" do
expect(test_user.name).to eq('Alice')
end
end
end
--output:--
$ rspec 1.rb
F
Failures:
1) MallSpec user's name equals 'Alice'
Failure/Error: let(:user) { FactoryGirl.build(:user) }
NameError:
uninitialized constant User
...
Run Code Online (Sandbox Code Playgroud)
添加以下定义User class:
require 'factory_girl'
#====NEW CODE=====
class User
attr_accessor :name, :age
end
#=================
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
FactoryGirl.define do
factory :user do
name 'Alice'
age 10
end
end
describe "MallSpec" do
let(:test_user) { FactoryGirl.build(:user) }
describe "user's name" do
it "equals 'Alice'" do
expect(test_user.name).to eq('Alice')
end
end
end
--output:--
$ rspec 1.rb
.
Finished in 0.0024 seconds (files took 0.35197 seconds to load)
1 example, 0 failures
Run Code Online (Sandbox Code Playgroud)
我期望这里的factory()方法:
factory :user do
name 'Alice'
age 10
end
Run Code Online (Sandbox Code Playgroud)
...做这样的事情:
def factory(model_name)
target_class = constant_get(model_name.capitalize)
Run Code Online (Sandbox Code Playgroud)
...为了构造 User 类的真实实例。换句话说,factory_girl 构造应用程序中已存在的类的实例——factory_girl 不会模拟类。
| 归档时间: |
|
| 查看次数: |
1769 次 |
| 最近记录: |