我正在使用 Rspec 和 selenium-webdriver gem 来测试网络应用程序。而且我想在我的测试中取消工厂以模拟用户而不是每次都手动创建用户。 所以,我做了 gem install factory_girl,在我的 spec_helper 中添加了 required 行,创建了一个工厂并在我的规范文件中包含了一些行。运行测试时出现错误 失败/错误:FactoryGirl.build(: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
我的 factory.rb 文件:
FactoryGirl.define do
factory :user do
name "testuser"
password "freestyle"
inventory true
end
end
还有我的 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
我的 spec_file 位于项目的根目录中。我的 factories.rb 文件在/spec 目录以及 test_spec.rb 本身。 谁能帮我解决这个问题或指出我做错了什么?
最佳答案
如果您实际上没有 User
类,但想使用 FactoryGirl 生成属性,则可以重写该类:
require "ostruct"
FactoryGirl.define do
factory :user, class: OpenStruct do
name "testuser"
password "freestyle"
inventory true
# This isn't necessary, but it will prevent FactoryGirl from trying
# to call #save on the built instance.
to_create {}
end
end
然后,如果您只想要一个Hash
,则可以使用attributes_for
,或者如果您想要一个响应等方法的对象,则可以使用
。create
>姓名
您可以使用类似 Hashie::Mash
的库如果您想生成 JSON 以在您的 API 中使用:
factory :user, class: Hashie::Mash do
# ...
end
# In your tests:
user_json = create(:user).to_json
关于ruby - Rspec + Factory girl(没有导轨!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670159/