我已经在Michael Hartl的Rails 3教程书中添加了回复微博功能,但我现在正在尝试为他们编写测试(我知道我做了倒退)。回复添加有效,但我正在尝试编写以下测试
我的测试目前在第四步失败了。以下是spec文件的片段,失败错误以及指向我的repo的链接。 (用户在此描述之前定义,但在此块的范围内)
describe "replying to a micropost" do
let (:other_user) { FactoryGirl.create(:user) }
let (:first_post) { FactoryGirl.create(:micropost, user: other_user, content: "Whatever.") }
let (:second_post) { FactoryGirl.create(:micropost, user: other_user, content: "Nevermind.") }
before do
user.follow!(other_user)
visit root_path
end
it "should render the posts from other user" do
page.should have_selector("li##{first_post.id}", text: first_post.content)
page.should have_selector("li##{second_post.id}", text: second_post.content)
end
Failures:
1) Static pages Home page for signed-in users replying to a micropost should render the posts from other user
Failure/Error: page.should have_selector("li##{first_post.id}", text: first_post.content)
expected css "li#203" with text "Whatever." to return something
# ./spec/requests/static_pages_spec.rb:85:in `block (5 levels) in <top (required)>'
Finished in 3.43 seconds
17 examples, 1 failure
Failed examples:
rspec ./spec/requests/static_pages_spec.rb:84 # Static pages Home page for signed-in users replying to a micropost should render the posts from other user
Done.
答案 0 :(得分:1)
简而言之,我的测试失败了,因为我需要用户让! (让bang)为了在let时创建微博!呼叫。使用简单的let调用(即没有!)直到page.should has_selector行才会创建微博,这是在访问root_path调用之后,因此在页面上找不到微博。
以下是我弄清楚的方法......它与此问题中迭代的语句相关,关于初始化之前的let vs,其中s / he表示“对于let定义的方法,初始化代码仅在示例调用时运行它。” (来源:stackoverflow.com/questions/5359558/when-to-use-rspec-let)在我的例子中,first_post和second_post没有被创建,直到我在have_selector中调用了他们的id('li'... call ,这意味着它们不会在访问root_path之后创建,因此在构建用户的feed后也是如此。我唯一需要支持这个假设的是,如果你添加一些像first_post.content = first_post.content(和在访问root_path调用之前,对于posts发生了