想象一下,我有这样的路线:
resource :users do
resource :projects
do
project.rb
...
belongs_to :users
...
user.rb
...
has_many :projects
...
如果我想为Project创建rspec测试,我是否会在没有用户的情况下单独测试Project?从理论上讲,没有用户就永远不会有项目,因为用户创建了一个项目。像这样:
project_spec.rb
...
it "is created by a user"
...
或
user_spec.rb
...
it "create a project"
...
如果我想为User创建Project进行测试,我会在user_spec或project_spec中进行吗?或两者兼而有之?
答案 0 :(得分:1)
我通常使用模拟进行隔离和速度。这些规范仅测试User对象的边界,并且不会使用Project模型命中数据库或执行任何实际操作。 他们测试行为而非州。
(以下使用RSpec 2.11功能)
describe User do
let(:project){ mock_model(Project) }
subject(:user){ User.new(:project => project) }
it "does something with a project" do
project.should_receive(:some_method_call).and_return(:a_value)
user.do_something
end
end
describe User do
let(:fake_project_class) { Class.new }
let(:project){ double('a_project') }
subject(:user){ User.new }
before(:each) do
stub_const("Project", fake_project_class)
end
it "creates a project" do
Project.should_receive(:new).and_return(project)
user.make_me_a_project!
end
end